function varargout=uistack(Handles,StackOpt)
%UISTACK Restack objects.
%   UISTACK(H) visually raises the visual stacking order of the objects, H. 
%   UISTACK(H,STACKOPT) where STACKOPT is 'up','down','top','bottom'
%   applies the stacking option to the handles specified by H. All
%   handles, H, must have the same parent.

%   Loren Dean
%   Copyright 1984-2000 The Mathworks, Inc. 
%   $Revision: 1.4 $ $Date: 2000/06/02 04:41:47 $

error(nargchk(0,1,nargout));
error(nargchk(1,2,nargin));
if ~all(ishandle(Handles)),
  error('Invalid Handles passed to UISTACK');
end
if nargin==1,
  StackOpt='up';
end

Parent=get(Handles,{'Parent'});
Parent=[Parent{:}];
UParent=unique(Parent);
if length(UParent)>1,
  error('All handles passed to UISTACK must have the same Parent.');
end

Children=allchild(UParent);
HandleLoc=find(ismember(Children,Handles));

switch StackOpt,
  case 'up',
    NewOrder=Children;
    for lp=1:length(Handles),
      Idx=HandleLoc(lp);
      if Idx~=1,
        NewOrder((Idx-1):Idx)= NewOrder(Idx:-1:(Idx-1));
      end
    end % for lp
    
  case 'down',
    NewOrder=Children;
    for lp=1:length(Handles),
      Idx=HandleLoc(lp);
      if Idx~=length(Children),
        NewOrder(Idx:(Idx+1))= NewOrder((Idx+1):-1:Idx);
      end
    end % for lp
    
  case 'top',
    Children(HandleLoc)=[];  
    NewOrder=[Handles;Children];
    
  case 'bottom',
    Children(HandleLoc)=[];  
    NewOrder=[Children;Handles];    
    
  otherwise,
    error('Invalid Stack option for UISTACK');
    
    
end % switch

% For figures, need to do something special
if isequal(UParent,0),
  for lp=length(NewOrder):-1:1,
    if strcmp(get(NewOrder(lp),'Visible'),'on'),
      figure(NewOrder(lp));
    end
  end
else,
  set(UParent,'Children',NewOrder);
end
  
if nargout,
  varargout{1}=NewOrder;
end