function ax = imgca(varargin)
%IMGCA Get handle to most recent current axis containing an image.
%   H = IMGCA returns the handle of the most recent current axis that
%   contains an image. The current axis may be in a regular figure 
%   window or in an Image Tool window.
%
%   If no figure contains an axis that contains an image, IMGCA creates a
%   new axis.
%
%   H = IMGCA(FIG) returns the handle to the current axis that contains 
%   an image in the specified figure (it need not be the current figure).
%
%   Note
%   -----
%   IMGCA can be useful in getting the handle to the Image Tool axis.
%   Because the Image Tool turns graphics object handle visibility
%   off, you cannot retrieve a handle to the tool figure using gca. 
%
%   Example
%   -------
%   Label the coins in the image, compute their centroids, and superimpose
%   the centroid locations on the image. View the results using IMTOOL and
%   IMGCA.
%
%       I = imread('coins.png');
%       figure, imshow(I)
%
%       bw = im2bw(I, graythresh(getimage));
%       figure, imshow(bw)
%
%       bw2 = imfill(bw,'holes');
%       L = bwlabel(bw2);
%       s  = regionprops(L, 'centroid');
%       centroids = cat(1, s.Centroid);
%
%       % Display original image I and superimpose centroids
%       imtool(I)
%       hold(imgca,'on')
%       plot(imgca,centroids(:,1), centroids(:,2), 'r*')
%       hold(imgca,'off')
%
%   See also GCA, GCF, IMGCF.
 
%   Copyright 1993-2004 The MathWorks, Inc.
%   $Revision: 1.1.10.1 $  $Date: 2004/08/10 01:49:04 $

iptchecknargin(0,1,nargin,mfilename);

if nargin==0
    fig = imgcf;
else
    fig = varargin{1};
    iptcheckhandle(fig,{'figure'},mfilename,'FIG',1)
end

if ~isempty(fig)
    currentAx = get(fig,'CurrentAxes');
    im = findobj(currentAx,'Type','image');
    if ~isempty(im)
        ax = currentAx;
    else
        % current axes doesn't contain any images
        [im,ax] = imhandles(fig);
        if ~isempty(ax)
            ax = ax(1);
        end
    end
end

if isempty(ax)
    ax = axes('parent',fig);
end