%Transforms mrx to mei by using the tranponent of the T-matrix in mei2mrx.m 
%
%Initial version: Niklas Edberg, Swedish Institute of Space Physics, Uppsala, Oct 2005

function mei = mrx2mei(mrx)

Ds = 52.876*pi/180; %Declination of north pole
Rs = 317.661*pi/180; %Right ascension of north pole
Do = 1.85*pi/180; %Inclination of mars orbit
Ao = 49.57854*pi/180; %Longitude of ascending node
Phi = 23.439291*pi/180; %Obliquity of spin axis

%This nice 3x3 matrix is the unnormalised transformation matrix

xa = cos(Ds)*sin(Rs)*(-sin(Do)*sin(Ao)*sin(Phi)+cos(Do)*cos(Phi)) - sin(Ds)*(sin(Do)*sin(Ao)*cos(Phi)+cos(Do)*sin(Phi));

xb = sin(Ds)*(-cos(Ao)*sin(Do)) - cos(Ds)*cos(Rs)*(-sin(Do)*sin(Ao)*sin(Phi)+cos(Do)*cos(Phi));

xc = cos(Ds)*cos(Rs)*(sin(Do)*sin(Ao)*cos(Phi)+cos(Do)*sin(Phi)) - cos(Ds)*sin(Rs)*(-cos(Ao)*sin(Do));

t = [ xa    xb     xc;
    (cos(Ds)*sin(Rs)*xc-sin(Ds)*xb)  (sin(Ds)*xa-cos(Ds)*cos(Rs)*xc)    (cos(Ds)*cos(Rs)*xb-cos(Ds)*sin(Rs)*xa);
    cos(Ds)*cos(Rs)     cos(Ds)*sin(Rs)     sin(Ds)];

 %And this is the normalised

 T(1,:) = t(1,:)./sqrt(t(1,1)^2 + t(1,2)^2 + t(1,3)^2);
 T(2,:) = t(2,:)./sqrt(t(2,1)^2 + t(2,2)^2 + t(2,3)^2);
 T(3,:) = t(3,:)./sqrt(t(3,1)^2 + t(3,2)^2 + t(3,3)^2);
 
for i=1:length(mrx)
    mei(:,i)=(T')*mrx(:,i);
end