function [hImage,hAxes,hFig] = imhandles(h)
%IMHANDLES Get all image handles within a handle.  
%   HIMAGE = IMHANDLES(H) takes a graphics handle H as an input and
%   returns all of the image handles whose ancestor is H. H can
%   be an array of valid figure, axes, image, or uipanel handles.
%
%   HIMAGE is an array of image handles. 
%  
%   Note
%   ----
%   IMHANDLES errors if the image objects in HIMAGE do not have the same
%   figure as their parent.
%
%   Examples
%   --------
%       figure,imshow('moon.tif');
%       hImage = imhandles(gca)
%
%       subplot(1,2,1),imshow('autumn.tif');
%       subplot(1,2,2),imshow('glass.png');
%       hImage = imhandles(gcf)

%   These undocumented syntaxes may change in the future.  
%   [HIMAGE,HAXES] = IMHANDLES(H) returns an array of axes handles
%   corresponding to HIMAGE. HAXES is a vector of axes handles.
%
%   [HIMAGE,HAXES,HFIG] = IMHANDLES(H) returns a figure handle that
%   contains HIMAGE and HAXES.

%   Copyright 1993-2004 The MathWorks, Inc.
%   $Revision.1 $  $Date: 2004/08/10 01:49:07 $

% set defaults
hImage = [];
hFig = [];
hAxes = [];

if ishandle(h)
  type = get(h,'Type');

  if all(strcmp(type,'image')) || all(strcmp(type,'figure')) || ...
        all(strcmp(type,'axes')) || all(strcmp(type,'uicontainer')) || ...
        all(strcmp(type,'uipanel'))

    hImage = findobj(h,'Type','image');
    hAxes = ancestor(hImage,'Axes');
    if iscell(hAxes)
      hAxes = [hAxes{:}]';
    end
    hFig = ancestor(h,'Figure'); %use h b/c hImage and hAxes could be empty

    % an array of images must belong to the same figure.
    if iscell(hFig) 
      if any(diff([hFig{:}]))
        eid = sprintf('Images:%s:invalidImageHandleArray',mfilename);
        msg = 'HIMAGE must belong to the same figure.';
        error(eid,'%s',msg);
      else
        hFig = hFig{1};
      end
    end

  else
    eid = sprintf('Images:%s:wrongKindOfGraphicsHandle',mfilename);
    msg = 'The handle must be a valid figure, axes, image, uicontainer, ';
    msg2 = 'or uipanel handle.';
    error(eid,'%s%s',msg,msg2);
  end
else
  eid = sprintf('Images:%s:invalidGraphicsHandle',mfilename);
  msg = 'The handle must be a valid graphics handle.';
  error(eid,'%s%s',msg);
end
