%function [xx,yy, field_out,spec] = spharm_filt_basis(lon, lat,field,xx,yy, trunc, basis, nnn, WW, norm, wn);

%wn is permitted wavenumbers;
%must run basissetup2 first

%routine to put the data into a gaussian quadrature grid and to preform the
%transform to the spherical harmonics, basis already established, to save
%time

[NN,N]=size(field);

num=trunc+1:-1:1; 
NNN=sum(num)+sum(num(2:length(num)));

[LON LAT]=meshgrid(lon,lat);
[XX YY]=meshgrid(xx*180/pi,yy*180/pi);



ifield=interp2(LON, LAT, field, XX, YY);

N=length(xx); %new dimensions of the guassian quadrature field
NN=length(yy);


for n=2:1:NNN
    spec(n,1)=sum(sum(basis(:,:,n).*WW.*ifield))/(norm(n));
end

field_out=zeros(NN,N);

WN=find(nnn>=min(wn) & nnn<=max(wn));

for n=1:1:length(WN)
    field_out=field_out+spec(WN(n),1)*basis(:,:,WN(n));
 
end



% figure(1); clf;
% subplot(2,1,1)
% load coast;
% axesm('robinson','MapLatLimit',[-90 90],'MapLonLimit',[0 360])
% load coast
% plotm(lat,long, 'k');hold on;
% hold on;
% pcolorm(LAT, LON, field-mean(mean(cos(LAT).*field))/mean(mean(cos(LAT))));
% color_trans; colormap(cmap);
% MAX=max(max(abs(field-mean(mean(cos(LAT).*field))/mean(mean(cos(LAT))))));
% caxis([-MAX MAX]);
% colorbar;
% 
% figure(1); hold on;
% subplot(2,1,2)
% load coast;
% axesm('robinson','MapLatLimit',[-90 90],'MapLonLimit',[0 360])
% load coast
% plotm(lat,long, 'k');hold on;
% hold on;
% color_trans; colormap(cmap);
% MAX=max(max(field_out));
% caxis([-MAX MAX]);
% pcolorm(YY,XX, field_out);
% colorbar;
% 
% 
% 
% colorbar
%title('output (contours) and input (colors)')
