%fix_s_end
%routine to edit out bottom spike in salt (& conductivity) data

stas=input('Which stations do you want to process?  ');
 [directory]=input('Enter the directory with the input grd mat file:  ','s');
 [outraw]=input('Now enter the directory where you want the new raw mat file to go:  ','s');

for i=1:length(stas)

matfmtfile=[directory,'/grd',sprintf('%4.4i',stas(i)),'.mat'];
newfile=[outraw,'/grd',sprintf('%4.4i',stas(i)),'.mat'];

disp(['   working on file ',matfmtfile]);

if(exist(matfmtfile)==2)

eval(['load ',matfmtfile]);

disp([' ']);
disp([' Zoom in to find the scan numbers bracketing the spike ']);
disp([' ']);
figure(1)
clf
plot(cave)
grid
zoom on
hold on
title('Conductivity');

figure(2)
clf
plot(s_ave)
grid
zoom on
hold on
title('Salinity')

figure(3)
clf
plot(s_ave,thetave);
grid
zoom on
hold on
plot(s_ave,thetave,'x');
xlabel('Salinity ');
ylabel('Theta ');


disp(['Now enter the min/max scan numbers to fit S(T) ']);
jstart=input(' First enter the starting scan scan number of the fit window ');
jstop=input('   Now enter the ending scan number of the fit window ');

disp([' ']);
kstart=input(' Next enter the starting scan number of the data you want replaced ');
disp([' routine will replace from there to the bottom of the profile ']);
maxp=max(pave);
kmax=find(pave==maxp);


x=[thetave(jstart:jstop)];
y=[s_ave(jstart:jstop)];
coefs=polyfit(x,y,1);
z=polyval(coefs,thetave);

s_ave(kstart:kmax)=z(kstart:kmax);
for m=kstart:kmax
cave(m)=sw_cndr(s_ave(m),tave(m),pave(m))...
.*sw_c3515.*(1+(6.5e-6).*(tave(m)-2.) - (1.5e-8).*(pave(m)-2000.));
end
thetave=sw_ptmp(s_ave,tave,pave,0);
sigthave=sw_pden(s_ave,tave,pave,0)-1000.;


figure(1)
plot([jstart:kmax],cave(jstart:kmax),'r');
figure(2)
plot([jstart:kmax],s_ave(jstart:kmax),'r');
figure(3)
plot(s_ave(jstart:kmax),thetave(jstart:kmax),'r');
plot(s_ave(kstart:kmax),thetave(kstart:kmax),'ko');

pause
eval(['save ',newfile,' ascan1 file pstop thetave ascan2 pave s_ave ', ...
'uave cave pedate sigthave vave cscan1 pgrid startdaytime wave cscan2 ', ...
'psdate stopdaytime dpdtave pstart tave']);
         


end; %if file exists
end; %i loop 

