function h = image(varargin)
%SAXS/IMAGE Display a SAXS image.
%   IMAGE(..., SAXS, ...) is the same as IMAGESC(...) except information
%   stored in the saxs image object SAXS helps control the image display.
%   The SAXS image object appears in the argument list wherever the image
%   array would appear in the equivalent call to IMAGESC or IMAGE.
%
%   If the SAXS image is collapsed (summed along an axis), IMAGE calls PLOT
%   to display the line. The SAXS argument must come first.  You may
%   include linespecs in the argument list.  See PLOT.
%
%   See also IMAGESC, IMAGE, COLORMAP, GETSAXS, SAXS, PLOT.

% First check if the image is collapsed.
if isa(varargin{1}, 'saxs')
    switch varargin{1}.type
        case {'xsum', 'ysum', 'rsum', 'thsum', ...
                'x-ave', 'r-ave', 'y-ave', 'th-ave'}
            hline = plot(varargin{:});
            if nargout > 0
                h = hline;
            end
            return
    end
end

% Okay, it must be a real image.

% Find the saxs image argument.
% It must be here or MATLAB wouldn't have called us.
% NB: we rely on all args being part of varargin.
% We pull the name of the saxs variable (if it is a variable)
% from the list by number.

for iarg = 1 : length(varargin)
    if isa(varargin{iarg}, 'saxs')
        sxname = inputname(iarg);  % keep the variable name
        sx = varargin{iarg};  % pull out the saxs object
        sxmax=max(max(sx.pixels)); % find the maximum
        sxmin=min(1,sxmax/100);
        varargin{iarg} = sx.pixels-sx.pixels.*(sx.pixels<sxmin);  % leave pixels in its place
        break
    end
end

% Things to do:
% Always use xaxis and yaxis;
% Use image type (xy (axis xy image) or rth (axis xy)). (labels)
% Color bar?
% Pull title from notes (file name, log(intensity)).
% Only unless caller ha' not specified those properties.  Yeah, right.

xaxis = sx.xaxis;
yaxis = sx.yaxis;

himage = imagesc(xaxis, yaxis, varargin{:});
if nargout
    h = himage;
end

% Straighten up the image.  This *should* be done with
% property substitutions in the call to imagesc.

hactual=get(himage, 'Parent');  

if sx.kcal
    distance_units = 'A^{-1*}';
else
    distance_units = 'pixels';
end

switch sx.type
case 'xy'
    axis(hactual,'image','xy')
    xlabel(hactual,['x, ', distance_units])
    ylabel(hactual,['y, ', distance_units])
    set(hactual,'DataAspectRatio',[1 1 1])
case 'rth'
    axis(hactual,'xy')
    xlabel(hactual,['momentum transfer, ', distance_units])
    ylabel(hactual,'azimuth, degrees')
otherwise  % never?
    axis(hactual,'image','xy')
end

% If we're plotting a saxs variable, show the name
% Show whether we're linear or logarithmic.
if sx.log
    scale = sx.log;
else
    scale = 'linear';
end
title(hactual,[sxname, ' (', scale, ' intensity)'],'Interpreter','none') 
