function [newX1, newX2, newX_v1, newX_v2] = rotpcs(x1, x2, X, X_v)
%% maximizing the distance between different groups by using Fisher criterion
% Input 
%      x1: The scores of the training set on PC#1 
%      x2: The scores of the training set on PC#2 
%      X: The scores of the training set
%      X_v: The scores of the test set
% Output
%      newX1: The scores of the training set on PC#1 after rotation
%      newX2: The scores of the training set on PC#2 after rotation
%      newX_v1:The scores of the test set on PC#1 after rotation
%      newX_v2: The scores of the test set on PC#2 after rotation


% compute means and scatter matrix
X1 = x1'; 
X2 = x2';
[mm,n1]=size(X1);
[mm,n2]=size(X2);

m1 = mean(X1,2); 
m2 = mean(X2,2);

S1 = (X1-m1*ones(1,n1))*(X1-m1*ones(1,n1))'; %centralize and square matrix
S2 = (X2-m2*ones(1,n2))*(X2-m2*ones(1,n2))';
Sw = S1 + S2;

% compute FLD 
W = inv(Sw)*(m1-m2);   

if abs(W(1))<10e-6,
    alpha = pi/2;
else 
    alpha = atan(W(2)/W(1));  
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
a = cos(alpha);
b = sin(alpha);
rotmatrix = [a, -b; b, a];

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
newx1 = x1*rotmatrix;
newx2 = x2*rotmatrix;
newX = X*rotmatrix;
newX_v = X_v*rotmatrix;%

if mean(newx1(:,1))>mean(newx2(:,1)),
    newx1 = -newx1; newx2 = -newx2; newX = -newX; newX_v = -newX_v; 
end
newX1 = newX(:,1);
newX2 = newX(:,2);
newX_v1 = newX_v(:,1);
newX_v2 = newX_v(:,2);

