function [x,y,a,state] = getimage(ax)
%GETIMAGE Get image data from axes.
%	A = GETIMAGE(AX) returns the image data for the first
%	image in the axes AX.  If AX doesn't contain an image, A will
%	be empty.  A is based on the CDATA property of the first
%	image and is converted into an indexed, intensity, or scaled
%	image so that A and B in the commands
%	   imshow(A), B = getimage(gca);
%	 will be the same.
%
%	[x,y,A] = GETIMAGE(AX) returns the image XDATA and YDATA
%	as well.
%
%	[A,FLAG] = GETIMAGE(AX) or [x,y,A,FLAG] = GETIMAGE(AX)
%	returns a FLAG indicating the type of image stored in AX.
%	FLAG is 1 for indexed images, 2 for intensity images, or
%	3 for scaled images.  FLAG is 0 if AX doesn't contain an 
%	image object.
%
%	[...] = GETIMAGE works with the current axes.

%	Clay M. Thompson 8-23-93
%       Copyright (c) 1993 by The MathWorks, Inc.
%       $Revision: 1.5 $  $Date: 1993/10/21 12:59:32 $

if nargin==0,
  if isempty(get(0,'ch')); state = 0; return; end
  if isempty(get(gcf,'ch')); state = 0; return; end
  ax = gca;
end

state = 0;
map = colormap;
h = get(ax,'children'); 
for i=1:length(h),
  if strcmp(get(h(i),'Type'),'image'),
     a = get(h(i),'Cdata');
     x = get(h(i),'Xdata'); y = get(h(i),'Ydata');
     cax = get(h(i),'UserData');
     if isempty(cax),
        state = 1;
     elseif all(cax==[0 1]),
        a = (a-1)/(size(colormap,1)-1);
        state = 2;
     else
        a = (a-1)*((cax(2)-cax(1))/(size(colormap,1)-1))+cax(1);
        state = 3;
     end
   elseif strcmp(get(h(i),'Type'),'surface'),
      if strcmp(get(h(i),'FaceColor'),'texturemap'),
         a = get(h(i),'Cdata');
         x = get(h(i),'Xdata'); y = get(h(i),'Ydata');
         state = 1; getcoords = 0;
      end
   end
end

if nargout<3,
  x = a; y = state;
end

