%                togrid4.m
%               for constructing ascii flat file with lon,lat,u(ind),v(ind)
%               where each of the variables is subsampled by 2

load latlon
load ghfactor.cal
im=sqrt(-1);
ghval=[1 2 3 4 5 6 7 9];
umean=[];
for k=1:8
     kk=ghval(k);
	disp(kk)
	uarray=[]; varray=[];
	eval(concat('load gh',int2str(ghval(k)),'cof.tid'))
	for i=1:7
		uarray(:,i)=subsamp(2,2,u0coef(:,i));
		varray(:,i)=subsamp(2,2,v0coef(:,i));
	end
%               rotate to common phase
	[uarray(:,2),uarray(:,3)]=rot(uarray(:,2),uarray(:,3),-phase(kk));
	[uarray(:,4),uarray(:,5)]=rot(uarray(:,4),uarray(:,5),-phase(kk)*2);
	[uarray(:,6),uarray(:,7)]=rot(uarray(:,6),uarray(:,7),-phase(kk)*3);
	[varray(:,2),varray(:,3)]=rot(varray(:,2),varray(:,3),-phase(kk));
	[varray(:,4),varray(:,5)]=rot(varray(:,4),varray(:,5),-phase(kk)*2);
	[varray(:,6),varray(:,7)]=rot(varray(:,6),varray(:,7),-phase(kk)*3);
%               adjust amplitude

	 uarray=uarray/mag(kk);
      varray=varray/mag(kk);
	
	[i,j]=size(umean)
	[inew,j]=size(uarray);
     ind=[i+1:i+inew];

	ucoef(ind,:)=uarray;
	vcoef(ind,:)=varray;

	umean(ind,3)=uarray(:,1);
	vmean(ind,3)=varray(:,1);

     um2(ind,3)=uarray(:,2);
     um2s(ind,3)=uarray(:,3);
     vm2(ind,3)=varray(:,2);
     vm2s(ind,3)=varray(:,3);

     um4(ind,3)=uarray(:,4);
     um4s(ind,3)=uarray(:,5);
     vm4(ind,3)=varray(:,4);
     vm4s(ind,3)=varray(:,5);

     um6(ind,3)=uarray(:,6);
     um6s(ind,3)=uarray(:,7);
     vm6(ind,3)=varray(:,6);
     vm6s(ind,3)=varray(:,7);
end
mean(:,1:2)=latlon;
um2(:,1:2)=latlon;
vm2(:,1:2)=latlon;
um4(:,1:2)=latlon;
vm4(:,1:2)=latlon;
um6(:,1:2)=latlon;
vm6(:,1:2)=latlon;

um2s(:,1:2)=latlon;
vm2s(:,1:2)=latlon;
um4s(:,1:2)=latlon;
vm4s(:,1:2)=latlon;
um6s(:,1:2)=latlon;
vm6s(:,1:2)=latlon;

save mean.all mean
save um2.all um2
save vm2.all vm2
save um4.all um4
save vm4.all vm4
save um6.all um6
save vm6.all vm6
save um2s.all um2s
save vm2s.all vm2s
save um4s.all um4s
save vm4s.all vm4s
save um6s.all um6s
save vm6s.all vm6s
