clear all;
DepLog = ReadDeploymentLog();
[missionIDs, idxunique] = unique(DepLog.("Deployment ID"));
missionIDs = cellstr(missionIDs);
depthnegative = NaN(length(missionIDs),1);
AdjustpHCorr = NaN(length(missionIDs),1);
mn_adj = NaN(length(missionIDs),1);
mn_noadj = NaN(length(missionIDs),1);
Cal_file_deltapHfit = NaN(length(missionIDs),1);
filetype = cell(length(missionIDs),1);
filetype(:) = {NaN};
depsum = DepLog.("Deployment summary")(idxunique);
for i = 1:length(missionIDs)
    %% Load 's' and 'Cal' from a deployment
    basepath = 'C:\Users\bwerb\Documents\SprayDataCorrections\CorrectedQCFiles';
    % try to read in the QC file. If that fails, try to read in the
    % calibrated file. If that fails just continue
    try
        fileName = fullfile(basepath,[char(missionIDs(i)),'_QC.mat']);
        load(fileName);
        filetype{i} = 'QC';
    catch
        continue
    end
    %%
    if mean(s.depth,'all','omitmissing') < 0
        depthnegative(i) = true;
        s.depth = -s.depth;
    elseif mean(s.depth,'all','omitmissing') > 0
        depthnegative(i) = false;
    end
    %% Create variables
    time = s.sdn;

    % pHin Corrected and QC'd
    pHcorr = s.pHcorr; % Drift adjustment applied
    pHcorr(pHcorr == -999) = nan;
    % pHin(s.pHin_QC ~= 1) = nan; % 1 means good data
    
    % pHin CanyonB estimate and QC'd
    pHin_CanB = s.pHin_canb;
    pHin_CanB(pHin_CanB == -999) = nan;
    % pHin_CanB(s.pHin_QC ~= 1) = nan;

    % pHin QC'd
    pHin = s.pHin; % Drift adjustment applied
    pHin(pHin == -999) = nan;
    
    pHincanB_residuals = pHin - pHin_CanB; % No correction applied
    pHcorrcanB_residuals = pHcorr - pHin_CanB; % Correction applied

    ncolorblocks = 60;
    ncolorblocksredblue = 30; % cbar range is 0.3. Each block is .01. White space is .02.
    
    depthidx = s.depth >= 440 & s.depth <= 460; % Depth of correction    
    mn_noadj(i) = mean(pHincanB_residuals(depthidx),'all','omitmissing');
    mn_adj(i) = mean(pHcorrcanB_residuals(depthidx),'all','omitmissing');
    %% Plotting: Residuals vs Depth
    cla; clf;
    fig = figure;
    tl = tiledlayout(1,2,"TileSpacing","compact","Padding","tight");
    title(tl,['Joint-PDF of pH Residuals vs depth for deployment ',char(missionIDs(i))]);
    ylabel(tl,'Depth (m)')
    xlabel(tl,'pH - CanyonB')
    
    nexttile
    hold on;
    histogram2(pHincanB_residuals,s.depth,"Normalization","pdf","DisplayStyle","tile",'FaceColor','flat','BinWidth',[.01 10])
    set(gca,'Ydir','reverse')
    grid on
    title('Pre-Correction')
    xline(0,'k-','LineWidth',1)
    % yline(450,'r-','LineWidth',2)
    shading("interp")
    clim([0 .04])
    % scatter(0,450,'o','filled','red')
    scatter(mn_noadj(i),450,'o','filled','red')
    legend('','',['mean 440-460m pHin: ', num2str(mn_noadj(i))],'FontSize',6,Location='northwest');
    ylim([0 round(max(s.depth,[],'all'),0)])

    nexttile
    hold on;
    histogram2(pHcorrcanB_residuals,s.depth,"Normalization","pdf","DisplayStyle","tile",'FaceColor','flat','BinWidth',[.01 10])
    set(gca,'Ydir','reverse')
    cb = colorbar;
    cb.Label.String = 'Probability Density';
    grid on
    title('Post-Correction')
    xline(0,'k-','LineWidth',1)
    % yline(450,'r-','LineWidth',2)
    shading("interp")
    clim([0 .04])
    % scatter(0,450,'o','filled','red')
    scatter(mn_adj(i),450,'o','filled','red')
    legend('','',['mean 440-460m pHcorr: ', num2str(mn_adj(i))],'FontSize',6,Location='northwest')
    ylim([0 round(max(s.depth,[],'all'),0)])

    % Link axes for same x and y limits
    ax = findall(fig, 'Type', 'axes');
    linkaxes(ax, 'xy');
    xMax = max(abs([xlim(ax(1))]));
    xlim(ax, [-xMax, xMax]);

    fsavename = fullfile('C:','Users','bwerb','Documents','SprayDataCorrections','FinalCorrectionFigures',['missionID_',char(missionIDs(i))]);
    set(gcf, 'PaperOrientation', 'landscape');
    set(gcf, 'PaperUnits', 'inches');
    set(gcf, 'PaperSize', [11 8.5]); % Standard letter size in landscape
    set(gcf, 'PaperPosition', [0 0 11 8.5]); % Fill the whole paper
    saveas(fig,fsavename,'png')
    disp(['Finished ',num2str(i), ' / ', num2str(length(missionIDs))])
    close('all')
end
%%
% Info = table(missionIDs, AdjustpHCorr, depthnegative, mn_noadj, mn_adj, filetype,Cal_file_deltapHfit, depsum,...
%           'VariableNames', {'MissionID', 'Need_pHCorr_Adjustment', 'Depth_negative', 'mean_residual450_noadj','mean_residual450_adj','filetype','Cal_file_deltapHfit','Deployment_Summary'});
% % Save the table as a CSV file
% writetable(Info,'Info.csv');