% Function called within update_GliderVIZ_sat.m
% Makes profile figures of real-time data, saves to Atlas project library,
% and sends as a jpg via email
% UPDATES:
% 7/18/2020, YT
% added plot for optical (Chl-a)
% 3/16/2022, JL
% Switched to using a loop for subplots, some visual updates, other
% efficiency updates


function [] = plot_spraysat(s, plotpath)

% Default plot settings
set(0, 'DefaultAxesFontSize', 20, ...
    'DefaultAxesLineWidth', 2, ...
    'DefaultLineLineWidth', 1, ...
    'DefaultTextFontName', 'Times', ...
    'DefaultAxesFontWeight', 'bold', ...
    'DefaultLineMarkerSize', 10, ...
    'DefaultFigureUnit', 'centimeter', ...
    'DefaultFigurePosition', [6 1 25 20]);

% Select graphing display options
w = 0.4; % length
l = 0.2; % width
ygap = 0.05;
xgap = 0.05;
xindent = 0.1;
yindent = 0.06;
fname = 'avenir';
fsize = 12;
msize = 4;
% New profile settings
newcol = rgb('crimson');
newlw = 2;

%% Start program
if(length(s.lat)<11)
    nplot = length(s.lat)-1;
else
    nplot = 10; % how many dives to plot
end
profs2plot = size(s.pres,2)-nplot:size(s.pres,2);
preslimits = [0 round(max(max(s.pres(:,profs2plot))),1)+10];

% Estimate glider drift at surface
POS1 = [s.lat_(1,end), s.lon_(1,end)]; %
POS2 = [s.lat_(2,end-1), s.lon_(2,end-1)]; %
dist = num2str(vector_distance_new(POS1,POS2))
timvece = datevec(s.sdn_(1,end) - s.sdn_(2,end-1))


% fit into a printable letter size paper
% figs = {'f1','f2'}; % Number of pages
for j = 1:2
    F(j) = figure('unit', 'inch', 'position', [0.1 0.6 8.5 14]);
    % Colors
    cm = colormap(cmocean('dense',11));
    cm = cm([2:11],:);
    % first subplot is map, m_mapV1.4 needs to be downloaded
    subplot('position', [0.15 0.82 0.35 0.17]);
    hold on; box on;
    m_proj('miller', 'lat', [min(s.lat)-0.5 max(s.lat)+0.5], 'lon', [min(s.lon)-0.5 max(s.lon)+0.5]); % set range for world map
    m_coast('color', [0 0 0]); % draw coast lines
    m_plot(s.lon(end-nplot:end), s.lat(end-nplot:end), 'k+', 'markersize', 1); % plot cruise tracks.
    m_plot(s.lon(end), s.lat(end), 'o', 'color', newcol,'markerfacecolor', newcol, 'markersize', 2); % plot last surface black
    set(gca, 'yticklabel', [], 'xticklabel', []); % erase x and y labels.
    xlabel('Lon', 'fontsize', fsize, 'fontname', fname);
    ylabel('Lat', 'fontsize', fsize, 'fontname', fname);

    fsize_tbl = 16;
    % top right is for text
    subplot('position', [0.55 0.82 0.4 0.17], 'visible', 'off');
    t1 = text(0, 0.9, [s.depID]);
    t2 = text(0, 0.7, ['DATE: ',datestr(min(s.sdn_(:)),'dd/mm/yyyy'),' to ',datestr(max(s.sdn_(:)),'dd/mm/yyyy')]);
    t3 = text(0, 0.5, ['Last profile: ',datestr(s.sdn(end))]);
    t4 = text(0, 0.3, [num2str(length(s.sdn)),' profiles']);
    t5 = text(0, 0.1, sprintf('%3.3f, %3.3f', s.lat(end), s.lon(end)));
    t6 = text(0, 1.1, ['Change at surface: distance = ' dist])
    t6 = text(0, 1.1, ['Change at surface: time = ' timevec()])
    set([t1,t2, t3, t4, t5], 'fontsize', fsize_tbl, 'fontweight', 'bold');

end

%% Make variable plots
F(1);
figure(1);
% ============= start plotting profiles ======================
% Set positioning for subplots
posvec = [xindent yindent+2*l+2*ygap w l;
    xindent+xgap+w yindent+2*l+2*ygap w l;
    xindent yindent+l+ygap w l;
    xindent+xgap+w yindent+l+ygap w l;
    xindent yindent w l;
    xindent+w+xgap yindent w l];
% Choose variables to plot
vars = {'tc','psal','doxy','pHin','opt','deltapH'};
vname = {'Temperature','Salinity','O_2 [umol/kg]','pH','Chl_a','pH_{in} - pH_{CANYONB}'};
xlims = [2,14;31,35;0,400;7,8.5;-1,20;-0.01 0.1];
s.deltapH = s.pHin - s.pHin_canb; % Define deltapH
s.deltapH_QC = s.pHin_QC; % Need to give it a QC field too

% Loop through variables and make subplots
for i = 1:length(vars)
    ax(i) = subplot('position',posvec(i,:));
    hold on; box on;
    var = char(vars(i));
    var2plot = s.(var);
    var2plot(s.([var '_QC'])~=0) = NaN;
    plot(var2plot(:,profs2plot), s.pres(:,profs2plot));
    plot(s.(var)(:,end), s.pres(:,end),'Color', newcol,'Linewidth',newlw);
    set(gca, 'ydir', 'reverse', 'fontsize', fsize, 'FontName', fname); %, 'YTickLabel', []);
    xlabel(char(vname(i)));
    xlim(xlims(i,:))
    ylim(preslimits);
end
linkaxes(ax, 'y');
% Set colormap for line profiles
set(ax,'ColorOrder',cm)
set(findall(F(1),'-property','Fontname'),'Fontname','Times','fontsize',fsize)

%% Make diagnostics plots

F(2);
figure(2);
% ============= start plotting profiles ======================
% Set positioning for subplots
posvec = [xindent yindent+2*l+2*ygap w l;
    xindent+xgap+w yindent+2*l+2*ygap w l;
    xindent yindent+l+ygap w l;
    xindent+xgap+w yindent+l+ygap w l;
    xindent yindent w l;
    xindent+w+xgap yindent w l];
% Choose variables to plot
vars = {'vrs_std','vrs','vk_std','vk','Ik','Ib'};
vname = {'Vrs std','Vrs','Vk std','Vk','Ik','Ib'};
xlims = [-0.5,0.5;-1.0,-0.5;-0.5,0.5;-2,-1;0,7;0.4,1];

% Loop through variables and make subplots
for i = 1:length(vars)
    ax(i) = subplot('position',posvec(i,:));
    hold on; box on;
    var = char(vars(i));
    var2plot = s.(var);
    plot(var2plot(:,profs2plot), s.pres(:,profs2plot));
    plot(s.(var)(:,end), s.pres(:,end),'Color', newcol,'Linewidth',newlw);
    set(gca, 'ydir', 'reverse', 'fontsize', fsize, 'FontName', fname); %, 'YTickLabel', []);
    xlabel(char(vname(i)));
    xlim(xlims(i,:))
    ylim(preslimits);
end
linkaxes(ax, 'y');
% Set colormap for line profiles
set(ax,'ColorOrder',cm)
set(findall(F(2),'-property','Fontname'),'Fontname','Times','fontsize',fsize)

%% Save figures
for i = 1:length(plotpath)

    f1filename = [plotpath{i},s.depID,'_sat_',num2str(size(s.pres,2)),'prof.jpg'];
    saveas(F(1), f1filename);
    tmp = [plotpath{i},s.depID,'_sat_',num2str(size(s.pres,2)),'prof.fig'];
    saveas(F(1), tmp); clear tmp

    f2filename = [plotpath{i},'pH_diagnostics\',s.depID,'_sat_',num2str(size(s.pres,2)),'diag.jpg'];
    saveas(F(2), f2filename);
    tmp = [plotpath{i},'pH_diagnostics\',s.depID,'_sat_',num2str(size(s.pres,2)),'diag.fig'];
    saveas(F(2), tmp);

end

pause(1);

% send file via email to Yui
% setpref('Internet', 'E_mail', 'yui@mbari.org');
% setpref('Internet', 'SMTP_Server', 'mail.mbari.org');
% 
% sendmail('yui@mbari.org', s.depID, 'Summary plots', ...
%     {f1filename,f2filename});

% send email to Jacki
% setpref('Internet', 'E_mail', 'jlong@mbari.org');
% setpref('Internet', 'SMTP_Server', 'mail.mbari.org');
% 
% sendmail('jlong@mbari.org', s.depID, 'Summary plots', ...
%     {f1filename,f2filename});

close(figure(1))
close(figure(2))



