How to close all/maximize all windows?

This routine should be pretty simple, but it doesn't work!
It is a generic event handler used to minimize all windows,
close all windows, etc, in an MDI app.
However, maximizing doesn't work at all, and I get GPF on closing!
What can be wrong?

Furthermore, as you see, I have to count the windows upwards as well as
downwards...this is because restoring acts funny with counting downwards.
Only half of the minimized windows would then get restored!
While minimizing doesn't work upwards...
I have also tried to put in some app.processmessages, without luck.

procedure TFormMain.ArrangeWindows(Sender: TObject);
var
   i: longint;
begin
   for i := 0 to (MDIChildCount - 1) do
      begin
         if (sender as TMenuItem).name = 'MIRestoreAll'  then
            MDIChildren[i].WindowState := wsNormal;
      end;
   for i := (MDIChildCount - 1) downto 0 do
      begin
         if (sender as TMenuItem).name = 'MIMinimizeAll' then
            MDIChildren[i].WindowState := wsMinimized;
         if (sender as TMenuItem).name = 'MIMaximizeAll' then
            MDIChildren[i].WindowState := wsMaximized;
         if (sender as TMenuItem).name = 'MICloseAll'    then
            MDIChildren[i].close;
      end;
end;

[Svein Olav Mytting, Sand, N-3075 Berger, Norway.  E-mail: bolle...@sn.no]