function [U,V]=getuEvN_uXvY(ui,vi,Acos,Asin,lon,lat,proj_ctr,hemis,hf_wflag,hfW,hfS);
%------------------------------------------------------------------------------
% function [U,V]=getuEvN_uXvY(ui,vi,Acos,Asin,lon,lat,proj_ctr,hemis,wflag,hfW,hfS)
%
% function to rotate cube_sphere [ui,vi] to [uE,vN] or [uX,vY], size [nx,ny]
%          Here, the last row of uE and last colm of vN are un-usable due to zero-padding!!
% input:
%  [ui,vi]  : velocity in cube-sphere coord, size [nx,ny] (unprimed)
%  [lon,lat]: [nx,ny] (unprimed)
%  [Acos,Asin]: rotational angles from cube-sphere to [lon,lat], size [nx,ny]
%  hemis    : 1=arctic, -1 = antarctic
%  proj_ctr : center longitude for llssmi1
%           : [-180,180]
%           : if = -1000, no [X,Y] projection will be done, [uE,vN] are returned.
%  hf_wflag : 1=use hfW & hfS, 0=just take (u_i + u_{i+1})/2 for centering
%  [hfW,hfS]: [nx,ny], needed if hf_wflag=1
%
%  ATN 013007, mod 041607, mod 24Aug2012 to add hfac_weight_flag hf_wflag
%------------------------------------------------------------------------------

i1=size(ui,1);
i2=size(ui,2);

u0=zeros(i1+1,i2);v0=zeros(i1,i2+1);
u0(1:i1,:)=ui;v0(:,1:i2)=vi;
if(hf_wflag==1);
  hfW0=ones(i1+1,i2);hfS0=ones(i1,i2+1);
  hfW0(1:i1,:)=hfW;  hfS0(:,1:i2)=hfS;
end;

%centering:
if(hf_wflag==0);
  u1=(u0(1:i1,:)+u0(2:i1+1,:))./2;
  v1=(v0(:,1:i2)+v0(:,2:i2+1))./2;
else;
  u1=(u0(1:i1,:).*hfW0(1:i1,:)+u0(2:i1+1,:).*hfW0(2:i1+1,:))./(hfW0(1:i1,:)+hfW0(2:i1+1,:));
  v1=(v0(:,1:i2).*hfS0(:,1:i2)+v0(:,2:i2+1).*hfS0(:,2:i2+1))./(hfS0(:,1:i2)+hfS0(:,2:i2+1));
end;
%rotating:
uE0=Acos.*u1-Asin.*v1;
vN0=Asin.*u1+Acos.*v1;

if(proj_ctr~=-1000);
  uE=uE0;%unprimed
  vN=vN0;%unprimed

  x=reshape(lon',i1*i2,1);y=reshape(lat',i1*i2,1);
  [uX,vY]=get_uXvY(reshape(uE',i1*i2,1),reshape(vN',i1*i2,1),x,y,proj_ctr,hemis);%primed
  U=reshape(uX,i2,i1);		%prime,verified i2,i1 order - 05.24.11
  V=reshape(vY,i2,i1);		%prime,verified i2,i1 order - 05.24.11
else;
  U=uE0;%			%unprimed
  V=vN0;%			%unprimed
end;

return
