depth_Nmax = ones(profi_num,1);
Tmax = ones(profi_num,1);
depth_Tmax = ones(profi_num,1);
depth_max = ones(profi_num,1);
S_Tmax = ones(profi_num,1);
depth_max(cast) = max(output{cast,5}(:,2));
% calculate pressure, absolute salinity and potential temperature
P = gsw_p_from_z(-depth(cast,:),lat); %pressure
SA = gsw_SA_from_SP(S(cast,:),P,lat,lon); %absolute salinity
pT = gsw_pt_from_t(SA,T(cast,:),P,0); %potential temperature
% calculate conservative temperature and the stability frequency
CT = gsw_CT_from_t(SA,T(cast,:),P); %conservative temperature
[N2, ~] = gsw_Nsquared(SA,CT,P,lat);
% the first stability maximum
index = find(diff_N2 >= 0);
while diff_N2(index(n)+1) >= 0
depth_Nmax(cast) = depth(1,index(n)+1);
pT(1:20) = -999; % rule out the upper 20 m
[Tmax(cast),index_Tmax] = max(pT);
depth_Tmax(cast) = depth(1,index_Tmax);
S_Tmax(cast) = S(cast,index_Tmax);
% Temporal variation of Tmax, D(Tmax) and S(Tmax)
set(f,'units','centimeters','position',[1,1,13*1.5,9*1.5],'color','w')
plot(year,Tmax,'.','MarkerSize',12)
ylabel('Tmax','FontWeight','bold')
set(gca,'FontSize',FontSize,'tickdir','out')
plot(year,depth_Tmax,'.','MarkerSize',12)
depth_max = floor(depth_max);
plot(year(depth_Tmax==depth_max),depth_Tmax(depth_Tmax==depth_max),'.','MarkerSize',12,'Color','r')
ylabel('D(Tmax)','FontWeight','bold')
set(gca,'FontSize',FontSize,'tickdir','out')
plot(year,S_Tmax,'.','MarkerSize',12)
ylabel('S(Tmax)','FontWeight','bold')
xlabel('Years','FontWeight','bold')
set(gca,'FontSize',FontSize,'tickdir','out')
set(f,'units','centimeters','position',[1,1,15.5*1.5,10*1.5],'color','w')
range = linspace(c_min,c_max,256);
[~,pos] = min(abs(depth_Tmax(n)-range));
plot(S_Tmax(n),Tmax(n),'.','color',color(pos,:),'MarkerSize',17)
xlabel('S(Tmax)','FontWeight','bold')
ylabel('Tmax (^{o}C)','FontWeight','bold')
title('D(Tmax) and Water Properties','FontWeight','bold')
set(gca,'FontSize',FontSize,'tickdir','out')
set(f,'units','centimeters','position',[1,1,12*1.5,9*1.5],'color','w')
m_proj('mercator','lon',[lon_start lon_end],'lat',[lat_start lat_end]);
m_grid('box','on','linest','none','fontname','times','linewidth',0.1,'tickdir','out','backcolor',[1 1 1],'Fontsize',20);
m_gshhs_h('patch',[0.6 0.6 0.6]);
range = linspace(c_min,c_max,256);
[~,pos] = min(abs(Tmax(n)-range));
m_plot(lon(n),lat(n),'.','color',color(pos,:),'markersize',20)
title('Spatial Distribution of Tmax')
set(gca,'fontsize',16,'color','w');