%% save output to a S2R formated file
%%  input file for modeling -- Dartmouth Collage's biological/physical model
%%   

%%  Kriging Software Package  version 1.0 beta,   October 29, 1998
%%  Copyright (c) 1998, property of Dezhang Chu and Woods Hole Oceanographic
%%  Institution.  All Rights Reserved.


if status < 4
   disp('No Kriging Data to interpolate !!')
else
[meshfilename, meshfilepath]=uigetfile('*.dat; *.txt; *.nod','Select an Input Node File');

if isstr(meshfilename)			% if file exists
   meshfilename1=[meshfilepath meshfilename ];
   qq=find(meshfilename == '.');
   if ~isempty(qq)
      indx2=qq(length(qq))-1;
   else
      indx2=length(meshfilename);
   end
   varname=meshfilename(1:indx2);
   eval(['load ' '''' meshfilename1 ''''])
   eval(['dat=' varname ';'])
end

meshnode=dat(:,1);
meshlong=dat(:,2);
meshlat=dat(:,3);
nmesh=length(meshlat);

if (min(meshlat) < ygmin | max(meshlat) > ygmax | min(meshlong) < xgmin |max(meshlong) > xgmax)
   hh=figure;
   set(hh,'unit','normalized','position',[0.2 0.35 0.6 0.2]);
   figure(hh);
   axis off
   text(0.1,0.8,'Node limits exceed the kriging map limits','sc');
   text(0.01,0.6,'        Node limits:','sc');
   text(0.2,0.6,sprintf('Latitude = [ %g ,  %g ]',min(meshlat),max(meshlat)),'sc');
   text(0.6,0.6,sprintf(' Longitude = [ %g ,  %g ]',min(meshlong),max(meshlong)),'sc');
   text(0.01,0.4,'Kriging Map limits:','sc');
   text(0.2,0.4,sprintf('Latitude = [ %g ,  %g ]',ygmin,ygmax),'sc');
   text(0.6,0.4,sprintf(' Longitude = [ %g ,  %g ]',xgmin,xgmax),'sc');
   hht=text(0.2,0.2,'Press anykey to continue ...','sc');
   pause
   close(hh);
else
   hh=figure;
   set(hh,'unit','normalized','position',[0.2 0.35 0.4 0.2]);
   figure(hh);
   hht=text(0.2,0.6,'Interpolating values to specified nodes.','sc');
   hht=text(0.2,0.4,'Please be patient ... ','sc');
   meshval=interp2(Xg,Yg,Cg,meshlong,meshlat);
   close(hh);
   tt=clock;
   year=tt(1);month=tt(2);day=tt(3);
   sec=round(3600*tt(4)+60*tt(5)+tt(6));			% time in seconds
   [s2rfilename, s2rfilepath]=uiputfile([truncated_filename '.s2r'],'Save Output S2R File As');
   if isstr(s2rfilename) == 1
      sr2fullfilename=[s2rfilepath s2rfilename ];
      qq=find(s2rfilename == '.');
      if ~isempty(qq)
        indx2=qq(length(qq))-1;
      else
        indx2=length(s2rfilename);
      end
      truncated_s2rfilename=s2rfilename(1:indx2);
      datestr=[num2str(day) ' ' num2str(month) ' ' num2str(year) ' ' num2str(sec)];
      fid = fopen(sr2fullfilename,'w');
      fprintf(fid,'%s\n',meshfilename1);
      fprintf(fid,'%s\n',datestr);
      for i=1:nmesh
         fprintf(fid,'%5d  %12.8e\n',meshnode(i),meshval(i));
      end
      fclose(fid);
   end
end
hs2rfile=findobj(gcf,'Tag','S2Rfile');
set(hs2rfile,'value',0);
end