function out = winmenu(fig)
%WINMENU Create a submenu for a "Window" menu item.
%	WINMENU constructs a submenu under the "Window" menu item
%	of the current figure.  The submenu can then be used to
%	change the current figure.  To use WINMENU, the "Window"
%	menu item must have its 'Tag' property set to 'winmenu'.
%
%	WINMENU(FIG) constructs the "Window" submenu for figure
%	FIG.
%
%	WINMENU('callback') returns the callback string to use in
%	the top-level uimenu item.
%
%	Example:
%	  fig_handle = figure;
%	  uimenu(fig_handle, 'Label', 'Window', ...
%	    'Callback', winmenu('callback'), 'Tag', 'winmenu');
%	  winmenu(fig_handle);  % Initialize the submenu
    
%	Steven L. Eddins, 6 June 1994
%	Copyright (c) 1984-94 by The MathWorks, Inc.
%	$Revision: 1.7 $  $Date: 1994/12/21 14:50:49 $

comp = computer;
comp = comp(1:2);

if (nargin == 1)
  % WINMENU('callback')
  if (isstr(fig))
    if (comp == 'PC')
      out = 'winmenu; drawnow';
    else
      out = 'winmenu';
    end
    return;
  end
end

if (nargin == 0)
  fig = gcf;
end

figs = findobj(get(0, 'Children'), 'flat', 'Visible', 'on');
figs = flipud(sort(figs));
h=findobj(fig, 'Tag', 'winmenu');
if (isempty(h))
  % No "Window" menu item for this figure!
  return;
end

if (comp == 'PC')
  % Method 1:  Works on the PC
  
  hKids = get(h, 'Children');
  if (length(hKids) > length(figs))
    delete(hKids(length(figs)+1:length(hKids)));
  else
    for k = length(hKids)+1:length(figs)
      uimenu(h);
    end
  end
  
  subMenus = get(h, 'Children');
  for k = 1:length(subMenus)
    figName = get(figs(k), 'Name');
    if (isempty(figName))
      figName = '[Untitled]';
    end
    set(subMenus(k), 'Label', ...
	sprintf('Fig. %d: %s', figs(k), figName), ...
	'Callback', ['figure(',num2str(figs(k)),')']);
  end
  
  drawnow;

else

  % Method 2:  Works on X and Mac.
  
  minKids = 15;

  numFigs = length(figs);
  hKids = get(h, 'Children');
  numKids = length(hKids);
  if (numKids < minKids)
    for k = numKids+1:minKids;
      uimenu(h);
    end
    numKids = minKids;
  end
  if (numKids < numFigs)
    for k = 1:2*(numFigs-numKids)
      uimenu(h);
    end
    numKids = numKids + 2*(numFigs-numKids);
  end
  
  % Get the children again to make sure we have the right order.
  hKids = get(h,'Children');
  
  % Set Visible property first to make this code work right on
  % the Mac.
  for k = 1:numFigs
    set(hKids(k), 'Visible', 'on');
  end
  for k = numFigs+1:numKids
    set(hKids(k), 'Visible', 'off');
  end
  
  for k = 1:numFigs
    figName = get(figs(k), 'Name');
    if (~length(figName))
      % figName is empty
      figName = '[Untitled]';
    end
    set(hKids(k), 'Label', sprintf('Fig. %d: %s', figs(k), figName), ...
	'Callback', ['figure(',num2str(figs(k)),')']);
  end
  
end
