%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% ctd plots %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%  Use UNESCO salinity and density calculations...  - JGB, 6/29/96
%
%  Reject bad data first....
%  mask = (data(:, sbe_temp_freq) > 15000) | (data(:, sbe_temp_freq) < 0);
%  data(mask, sbe_temp_freq) = ones(size(data(mask, sbe_temp_freq))) * NaN;
%  mask = (data(:, sbe_cond_freq) > 15000) | (data(:, sbe_cond_freq) < 0);
%  data(mask, sbe_cond_freq) = ones(size(data(mask, sbe_cond_freq))) * NaN;
%  clear mask;
%
%  Correct for difference in position of pressure sensor & cond/temp cells
%  and attitude of vehicle.  Note that roll not acounted for....

ok = find(~isnan(data(:, water_temp)));

dx = 0.8; dy = 0.25;
ctd_depth = data(:, m_depth) - (dx .* sin(data(:, m_pitch)) + dy .* cos(data(:, m_pitch)));

%  Correct for time lag of CTD due to pumbing.

nn = length(ctd_depth);  lag = 5;
ctd_depth(lag:nn) = ctd_depth(1:nn-lag+1);
for i=1:lag-1, ctd_depth(i)=ctd_depth(lag); end;

%  Convert m of freshwater to decibars  (from JWB 05/02/95)
% (3.281 ft/m)*(12 in/ft)*(2.49082e-2 dBar/in of H2O)

ctd_depth = ctd_depth(ok)*3.281*12*2.49082e-2;
cond = data(ok, water_cond);
temp = data(ok, water_temp);
ctd_time = data(ok, m_present_time);

n = length(cond);

ctd_time = ctd_time(1:n-s_lag);
temp = temp(1:n-s_lag); 
cond = cond((s_lag+1):n);
ctd_depth = ctd_depth(1:n-s_lag);

salt = sw_salt(10*cond/sw_c3515,temp,ctd_depth);
dens = sw_dens(salt, temp, ctd_depth);

%  If desired, output the time and CTD for gridding by Spyglass...

%if (exist( 'ctd_to_spy' ) == 1),
% if (ctd_to_spy == 1),
%	out(:,1)=data(ok, m_present_time);
%	out(:,2)=-ctd_depth;
%	out(:,3)=data(ok, water_temp);
%	out(:,4)=salt;
%	out(:,5)=dens;
%	fid = fopen(['col_ctd.' run_name], 'wt');
%	fprintf(fid, '%9.4f %9.4f %9.4f %9.4f %9.4f\n', out');
%	fclose(fid);
%	clear out;
%  end;
%end;

figure
set( gcf, 'name', 'Temperature and Salinity Plots' );
subplot(211);
hold off;
plot(ctd_time, temp, 'r.');
hold on;
grid on
title(['Temperature vs time ',run_name]);
ylabel('degrees C');
xlabel('seconds');
subplot(212);
hold off;
plot(ctd_time, salt, 'r.');
hold on;
grid on
title(['Salinity vs time ',run_name]);
ylabel('psu');
xlabel('seconds');
zoom on

figure
set( gcf, 'name', 'Temperature, Salinity, Density Plots II' );
subplot(131);
hold off;
plot(temp, ctd_depth, 'b-');
set(gca, 'ydir', 'reverse', 'ylim', [0 inf] )
hold on;
grid on;
title(['Temperature vs depth ']);
xlabel('degrees C');
ylabel('depth (m)');
subplot(132);
hold off;
plot(salt, ctd_depth, 'b-');
set(gca, 'ydir', 'reverse', 'ylim', [0 inf] )
hold on;
grid on
title(['Salinity vs depth ',run_name]);
xlabel('psu');
ylabel('depth (m)');
subplot(133);
hold off;
plot(dens, ctd_depth, 'b-');
set(gca, 'ydir', 'reverse', 'ylim', [0 inf] )
hold on;
grid on
title(['Density vs depth ']);
xlabel('kg/m^3');
ylabel('depth (m)');
zoom on
