%% To check if hysteresis is T and S both
clear all;
auvpath
x9826519

osal =sal;

temp = data(:,water_temp);
depth = data(:,m_depth);

%% Remove junk
idx = find(temp > 18.1); temp(idx)=NaN*idx;
Sdown = sal(going_down); Zdown = depth(going_down);
idx = find(Zdown<10 & Sdown < 30.7); Sdown(idx)=NaN*idx;
sal(going_down) = Sdown;

figure;
subplot(121); h1 = gca;
abc = temp; abc(going_down) = NaN; plot( abc, depth, 'r');
hold on
abc = temp; abc(going_up) = NaN; plot( abc, depth, 'b' ); 
xlabel( 'Temperature (^{o}C)')
ylabel( 'Depth (m)' );
zoom on

subplot(122); h2 = gca;
abc = sal; abc(going_down) = NaN; plot( abc, depth, 'r' );  
hold on;
bc = sal; abc(going_up) = NaN; plot( abc, depth, 'b' );
xlabel( 'Salinity (psu)')
zoom on

set( [h1 h2], 'YDir', 'reverse' );

iZ = [4:2:34];
Zdown = depth(going_down); Zup = depth(going_up);
Sup = sal(going_up); Sdown = sal(going_down); 
Tup = temp(going_up); Tdown = temp(going_down); 

for Z = 1:length(iZ);

 idx = find(Zdown >= iZ(Z)-1 & Zdown < iZ(Z)+1);
 cS = Sdown(idx); cT = Tdown(idx); cS(isnan(cS))=[]; cT(isnan(cT))=[];
 S_d(Z) = mean(cS); T_d(Z) = mean(cT); nS_d(Z) = length(cS); nT_d(Z) = length(cT);

 idx = find(Zup >= iZ(Z)-1 & Zup < iZ(Z)+1);
 cS = Sup(idx); cT = Tup(idx); cS(isnan(cS))=[]; cT(isnan(cT))=[];
 S_u(Z) = mean(cS); T_u(Z) = mean(cT); nS_u(Z) = length(cS); nT_u(Z) = length(cT);

end

figure(1); clf; set(gcf,'color','w','position',[20 400 1000 500]);

subplot(131);
plot(T_d,iZ,'b'); hold on; plot(T_u,iZ,'r');
legend('going down','going up');
set(gca,'YDir', 'reverse','fontweight','bold');
xlabel('Temperature');
ylabel('Depth (m)');

subplot(132);
plot(S_d,iZ,'b'); hold on; plot(S_u,iZ,'r');
legend('going down','going up');
set(gca,'YDir', 'reverse','fontweight','bold');
xlabel('Salinity');
ylabel('Depth (m)');

subplot(133);
plot(T_d-T_u,S_d-S_u,'k*'); 
set(gca,'fontweight','bold');
ylabel('Salinity: down-up');
xlabel('Temperature: down-up');

axes('position',[0 0 1 1]); set(gca,'visible','off','color','none');
t=text(.5,.95,'Mission x9826519, Mass. Bay, average of 8 down-up cycles in ~25 minutes');
set(t,'fontweight','bold','fontsize',15,'horizontalalignment','center');
