function so = crop(si, box)
%SAXS/CROP Crop a SAXS image to a rectangle.
%   CROP(S, BOX) returns a SAXS image made from SAXS image S, cropped to
%   the coordinates in BOX.  BOX is a 2 x 2 array: [xmin ymin; xmax ymax].
%   Coordinates are in terms of current axis values, not necessarily pixels.

if ~ isa(si, 'saxs')
    error('First argument must be a SAXS image object.')
end
if ~ (isnumeric(box) & size(box) == [2, 2] ...
        & box(1,1) < box(2,1) & box(1,2) < box(2,2))
    error('Second argument should be [xmin, ymin; xmax, ymax].')
end

pbox = pixel(si, box);  % nearest pixels

vbox = axiscoords(si, pbox);  % axis values after pixel rounding

so = si;
so.pixels = so.pixels(pbox(1,2):pbox(2,2), pbox(1,1):pbox(2,1));
so.xaxis = vbox(:, 1)';
so.yaxis = vbox(:, 2)';
event = sprintf('crop to axis values [%g, %g; %g, %g]', ...
    box(1,1), box(1,2), box(2,1), box(2,2));
event2 = sprintf('>to pixels [%d, %d; %d, %d]', ...
    pbox(1,1), pbox(1,2), pbox(2,1), pbox(2,2));
so.history = strvcat(so.history, event, event2);
