function p = pixel(s, coord)
%SAXS/PIXEL Return pixel coordinates nearest given x,y coordinates.
%   P = PIXEL(S, [X Y]) returns pixel coordinates [COLUMN, ROW]
%   closest to the given axis coordinates in the SAXS image object S.
%   If X or Y is outside the image, the nearest edge pixel is returned.
%
%   Multiple rows of [X Y] return multiple rows in P.

[nrows ncols] = size(s.pixels);
p(:, 1) = nearest(ncols, s.xaxis, coord(:, 1));
p(:, 2) = nearest(nrows, s.yaxis, coord(:, 2));


function pixelnum = nearest(npixels, axis, axisvalue)
%PIXELNUM Find nearest pixel to an axis value.
if isempty(axis)  % no axis, pixel numbers are axis coordinates
    axis = [1, npixels];
end
first = axis(1);
last = axis(2);
step = (last - first) / (npixels - 1);
pixelnum = interp1(first : step : last, 1 : npixels, axisvalue, 'linear', 'extrap');
pixelnum = floor(pixelnum+0.5);