clear all; close all;

gdata = readtable("Diel_GPP_log.csv");
for i = 1:height(gdata)
    filename = char(gdata.Filename(i));
    load(filename, 's'); % .mat file
    
    idiel = gdata.StartProf(i):gdata.EndProf(i);
    iupper = 1:5;
    s.o2satconc = reshape(calcO2sat(s.tc(:), s.psal(:)), size(s.pres));
    s.o2anom = s.doxy - s.o2satconc;
    meano2anom = mean(s.o2satper(iupper,idiel),1);
    sdn = s.sdn(idiel)-7/24;
    % dt = datetime(datevec(sdn));
    % dt.TimeZone = 'UTC';
    % dt.TimeZone = 'America/Los_Angeles';
    % sdn = datenum(dt)';
    % 
    
    [diel, SDNs] = parse_to_diel(sdn, meano2anom, 24);
    LegendNames = cellstr(datestr(SDNs, 'mm/dd/yy'));
    
    % amp = max(diel,[],2,'omitmissing') - ...
    %     min(diel,[],2,"omitmissing");
    amp = range(diel,1);
    
    fig1 = figure('Visible','off');
    tl = tiledlayout(3,1);
    title(tl,['Glider Mission ID: ', num2str(gdata.MissionID(i))])
    subtitle(tl,['Mean O_2 Anom Diel Cycle ', char(gdata.StartDate(i)), ' to ', char(gdata.EndDate(i))])
    nexttile
    plot(sdn,meano2anom,'.')
    datetick('x',6)
    ylabel('O2sat amplitude')
    xlabel('date')
    title('Mean O_2 Anom full time series')
    xticks auto
    
    nexttile
    plot(0:23,diel,'.')
    hold on
    LegendNames{end+1} = 'mean';
    plot(0:23,mean(diel,1,"omitmissing"),'-')
    legend(LegendNames,Location='eastoutside')
    ylabel('O2sat amplitude')
    xlabel('Local Time hrs')
    xticks([0 6 12 18 23])
    xticklabels({'00:00', '6:00', '12:00', '18:00', '00:00'});
    xlim([0 23])
    title('diel cycle by day')
    
    nexttile
    % plot(0:23,amp,'o','Color','k')
    bar(0:23,amp)
    ylabel('O2sat amplitude')
    xlabel('Local Time hrs')
    title('proxy for GPP')
    xlim([0 23])
    xticks([0 6 12 18 23])
    xticklabels({'00:00', '6:00', '12:00', '18:00', '00:00'});
    
    exportgraphics(fig1,'GliderO2Diels.pdf', 'ContentType', 'vector', 'Append', true);
end