% ROTATE: Given a configuration of points, rotates a 2D configuration about 
%         a given point by a specified angle (in radians).
%
%     Usage: newpts = rotate(pts,theta,{pivot})
%
%         pts =    [N x 2] matrix of coordinates of point configuration.
%         theta =  angle by which configuration is to be rotated; a positive 
%                    angle rotates the configuration counterclockwise, a 
%                    negative angle rotates it clockwise.
%         pivot =  optional 2-element vector of coordinates of the pivot point
%                    [default = centroid].
%         --------------------------------------------------------------------
%         newpts = [N x 2] matrix of registered & rotated points.
%

% RE Strauss, 6/26/96

function newpts = rotate(pts,theta,pivot)
  if (nargin < 3) pivot = []; end;

  N = size(pts,1);                        % Number of points

  if (isempty(pivot))
    [area,perim,pivot] = polyarea(pts);   % Use centroid for pivot
  end;

  pts = pts - ones(N,1)*pivot;            % Zero-center on pivot
  dev = angledev([-1 0],[0 0],pts,1);     % Angular deviations of pts from horizontal
  dev = dev + theta;                      % Add angle of rotation to deviations
  r = sqrt(pts(:,1).^2 + pts(:,2).^2);    % Distances of pts from origin

  newpts = zeros(size(pts));
  newpts(:,1) = r.*cos(dev) + pivot(1);   % New rectangular coordinates,
  newpts(:,2) = r.*sin(dev) + pivot(2);   %   restoring pivot

  return;

