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;
    pH = mean(s.pH25atm(iupper,idiel),1,"omitmissing");
    sdn = s.sdn(idiel)-7/24;
    
    [diel, SDNs] = parse_to_diel(sdn, pH, 24);
    LegendNames = cellstr(datestr(SDNs, 'mm/dd/yy'));
    
    fig1 = figure('Visible','off');
    tl = tiledlayout(3,1);
    title(tl,['Glider Mission ID: ', num2str(gdata.MissionID(i))])
    subtitle(tl,{['pH Diel Cycle ', char(gdata.StartDate(i)), ' to ', char(gdata.EndDate(i))],...
        ['Mean Layer: ', num2str(abs(s.depth(iupper(1)))), ' m - ', num2str(abs(s.depth(iupper(end)))), ' m']})
    nexttile
    plot(sdn,pH,'.')
    datetick('x',6,'keeplimits')
    ylabel('pH 25C')
    xlabel('date')
    title('pH full time series')
    
    nexttile
    plot(0:23,diel,'.')
    legend(LegendNames,Location='eastoutside')
    ylabel('pH 25C')
    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,mean(diel,1,"omitmissing"),'.')
    ylabel('pH 25C')
    xlabel('Local Time hrs')
    title('mean diel cycle')
    xlim([0 23])
    xticks([0 6 12 18 23])
    xticklabels({'00:00', '6:00', '12:00', '18:00', '00:00'});

    diels(i,:) = mean(diel,1,"omitmissing");
    exportgraphics(fig1,'GliderpHDiels.pdf', 'ContentType', 'vector', 'Append', true);

end
ii = gdata.MissionID ~= 21903401;
tot_mean_diel = mean(diels(ii,:),1,"omitmissing");

fig1 = figure('Visible','off');
title('Overall Mean Diel Cycle')
plot(0:23,tot_mean_diel,'.')
ylabel('pH 25C')
xlabel('Local Time hrs')
title('mean diel cycle')
xlim([0 23])
xticks([0 6 12 18 23])
xticklabels({'00:00', '6:00', '12:00', '18:00', '00:00'});

exportgraphics(fig1,'GliderpHDiels.pdf', 'ContentType', 'vector', 'Append', true);