%
%--------------------------------------------------------------------------
% function [data_out]=FT_rotate_2D(data_in, alpha, rcenter)
%
% A function for Matlab which rotates a 2D data grid by an angle alpha.
%
% data_in:   2D data grid
% alpha:     rotation angle given in degrees
% rcenter:   2D vecor, indicates center of rotation
%
% data_out:  2D data grid
%
% Andreas Freise  23.07.2009
%--------------------------------------------------------------------------
%

% Description: Rotates a 2D data grid by a given angle
% Keywords: rotate, 2D, angle

function [data_out]=FT_rotate_2D(data_in, alpha, rcenter)

  baseid='rotate_2D';
  
  phi=alpha/180*pi;
  
  M_rot=[cos(phi), -sin(phi); sin(phi), cos(phi)];

  [rows,cols]=size(data_in);
  x=(linspace(1,cols,cols)-rcenter(2));
  y=(linspace(1,rows,rows)-rcenter(1));
  [Grid.X,Grid.Y] = meshgrid(x,y);
    
  Coords=[Grid.X(:),Grid.Y(:)];
  Coords_new=M_rot*Coords';
  Coords_new=Coords_new';
  Coords(:,1)=round(Coords(:,1)+rcenter(2));
  Coords(:,2)=round(Coords(:,2)+rcenter(1));
  Coords_new(:,1)=round(Coords_new(:,1)+rcenter(2));
  Coords_new(:,2)=round(Coords_new(:,2)+rcenter(1));
 
  data_out=zeros(3*rows,3*cols);
  idxx1=find(Coords_new(:,1)>=1);
  idxy1=find(Coords_new(:,2)>=1);
  idxx2=find(Coords_new(:,1)<cols+1);
  idxy2=find(Coords_new(:,2)<rows+1);
  idx1=intersect(idxx1,idxy1);
  idx2=intersect(idxx2,idxy2);
  idx=intersect(idx1,idx2);

  for j=1:length(idx)
    i=idx(j);
    %disp(sprintf('%d: %d %d, %d %d\n', i,Coords_new(i,1),Coords_new(i,2),    Coords(i,1),   Coords(i,2)));
    data_out(Coords_new(i,2),Coords_new(i,1))=data_in(Coords(i,2),Coords(i,1));
  end

  

    

