function obj = rotatexy(obj0, degrees)
%SAXS/ROTATEXY Rotate a SAXS image in rectangular coordinates.
%   OBJ = ROTATEXY(OBJ0, DEGREES) takes a SAXS image OBJ0, in rectangular
%   coordinates, rotates it counterclockwise DEGREES degrees around its
%   center, and returns the rotated SAXS image object OBJ.  The dimensions
%   and pixel spacing of OBJ are the same as OBJ0.  The corners of OBJ0 are
%   lost, rotated out of the rectangle.  The corners of OBJ are filled with
%   NaN values where no image data is available from OBJ0.  The rotated
%   pixel intensities of OBJ are computed by interpolating in OBJ0.

[X,Y] = meshgrid(xdata(obj0), ydata(obj0));  % complete set of x,y coordinates
radians = degrees * 2 * pi / 360;
% Get the polar coordinates of our x,y data set.
[TH,R] = cart2pol(X,Y);
% Positive rotation is counterclockwise.  We shift our sampling grid
% clockwise.  We'll bring those sampled points to the original data point
% locations to achieve counterclockwise rotation.
TH = TH - radians;
% Translate the rotated polar coordinates to x,y position to sample out of
% the original image.
[XI,YI] = pol2cart(TH,R);
% Sample the original image.  Any point outside the original image becames
% NaN.
ZI = interp2(X,Y,obj0.pixels,XI,YI,'*l');
% Put the new intensity values in the SAXS object, leaving the old
% coordinates.  Voila.
obj = obj0;
obj.pixels = ZI;
obj = history(obj, ['rotate by ', num2str(degrees), ' degrees']);
