%% Notes
% Should add another loop that does the downcast.
% Should add plots that show residuals
% Should deal with the filenames and processing and save location
% in a more robust manor
%%
clear variables; % Clear all variables from workspace
close all; % Close all figure windows
%% Read in new RSK file from deployment
[filename, pathname] = uigetfile; % Select RBR file
file = fullfile(pathname,filename); % Build full file name
RSKprofiles = ReadRSKfile(file);
%% Make a directory to save figures
root = 'C:\Users\bwerb\Documents\RBRTests\Testfolder'; % Modify this as needed
cruiseName = char(filename(1:end-4));
folderName = fullfile(root,[cruiseName,'_figures']);
mkdir(folderName); % Create folder for figures
%% Load data from the MBTS cruise time series (BOG)
% BOGfile = 'BOGDatafake.xlsx';
% BOG = loadBOG(BOGfile); % DIC, Alk, TA, pH, psal, doxy, Temp
BOG = loadBOG(); % DIC, Alk, TA, pH, psal, doxy, Temp
BOG2 = readtable('\\atlas\BOG_Archive\DataArchives\Regions\NortheastPacific\CruiseData\NutrientAnalysisRFA\RFA_DATA\All_2018.xlsx');% \\atlas\BOG_Archive\DataArchives\Regions\NortheastPacific\CruiseData\NutrientAnalysisRFA\RFA_DATA\all_2018.xls
BOG2.DATE_TIME.TimeZone = "UTC";
% \\atlas\BOG_Archive\DataArchives\Regions\NortheastPacific\CruiseData\NutrientAnalysisRFA\RFA_DATA\pctd_2017.xls
% implement date check here
%% Loop through each profile and create figures
% If there is a matching cast in the BOG data then overlay the bottle
% and underway CTD data on the plot. The start time (tstart) from the 
% RBR downcast should match the BOG datetime value within a few minutes.
nprofiles = length(RSKprofiles.profiles.upcast.tstart); % number of profiles
for profile = 1:nprofiles
    castidx = getdataindex(RSKprofiles, profile, 'up'); % upcast index
    maxprofiledepth = max(RSKprofiles.data(castidx).values(:,10)); % 10 is depth
    if maxprofiledepth < 50 % Incomplete cast. Skip to next cast. This can happen for a variety of reasons (Niskin bottle fail, etc...)
        continue
    end
    RSKprofiledatetime = datetime(...
        datevec(RSKprofiles.profiles.downcast.tstart(profile)),...
        'TimeZone','UTC'); % Extract the downcast tstart
    [MatchingCastIndexBOG, mintimeBOG] = matchingCastIndices(BOG.DATE_TIME, RSKprofiledatetime); % What is BOG vs BOG2
    [MatchingCastIndexBOG2, mintimeBOG2] = matchingCastIndices(BOG2.DATE_TIME, RSKprofiledatetime); % Can set up BOG SQL to replace this step

    clf; cla % clear all figures and axes to avoid overplotting data

    % RBR data channels to plot
    [L, A] = RSKplotprofiles(RSKprofiles, 'channel',...
        {'Temperature1', 'Salinity','Dissolved O21',...
        'Chlorophyll-a1','Chlorophyll-a2',...
        'Backscatter'},'profile',profile,...
        'direction','up','reference','depth');
    % https://rbr-global.com/wp-content/uploads/2024/08/RBR-Sensors-RIG-0008817revK.pdf
    hold(A,'on') % Edit figure
    ylim(A,[1 500]) % Remove in air sample to improve autolims
    % Overwrite automatic titles
    % title(A,'RBR vs BOG',['\Deltat RBR and BOG profiles: ', string(mintimeBOG)])
    fontsize_title = 12;
    title(A(1),'Temperature'); % change the font size of the titles
    title(A(2),'Salinity');
    title(A(3),'Dissolved Oxygen')
    title(A(4),'Chlorophyll-a1')
    title(A(5),'Chlorophyll-a2')
    title(A(6),'Backscatter')
    % Remove 'Depth' ylabels for plots after 1
    ylabel(A(2),''); yticklabels(A(2),'')
    ylabel(A(3),''); yticklabels(A(3),'')
    ylabel(A(4),''); yticklabels(A(4),'')
    ylabel(A(5),''); yticklabels(A(5),'')
    ylabel(A(6),''); yticklabels(A(6),'')
    % Add extra information in subtitle
    clear sbtitle % Clear variable in between loop iterations
    clear SiteID
    sbtitle = {};
    if any(MatchingCastIndexBOG) % Add BOG data to plot if it exists
        scatter(A(1),BOG.tc(MatchingCastIndexBOG),...
            BOG.DEPTH(MatchingCastIndexBOG),10,'or','filled') % TC
        scatter(A(2),BOG.psal(MatchingCastIndexBOG),...
            BOG.DEPTH(MatchingCastIndexBOG),10,'or','filled') % PSAL
        scatter(A(3),BOG.doxy(MatchingCastIndexBOG),...
            BOG.DEPTH(MatchingCastIndexBOG),10,'or','filled') % doxy winkler
        scatter(A(4),BOG2.CHLA(MatchingCastIndexBOG2),...
            BOG2.DEPTH(MatchingCastIndexBOG2),10,'or','filled') % Chla CTD
        scatter(A(4),BOG2.CHL_GFF(MatchingCastIndexBOG2),...
            BOG2.DEPTH(MatchingCastIndexBOG2),10,'r','filled') % Chla discrete bottle
        % scatter(A(6),BOG2.TransBeam(MatchingCastIndexBOG2),...
        %     BOG2.DEPTH(MatchingCastIndexBOG2),5,'or','filled') % units
        mintimeBOG.Format = "m"; % Format minutes
        mintimeBOG2.Format = "m"; % Format minutes
        % sbtitle(end+1) = {'\Deltat: ' + string(mintimeBOG)};
        SiteID = strrep(BOG.SITE_ID(MatchingCastIndexBOG),' ',''); % 
        % Remove spaces
        SiteID = SiteID(1); % Get the site ID name
        subtitle(A(:),sbtitle) % Append sbtitle
        lg = legend(A(1),'RBR','BOG',Location='southeast');
        lg.FontSize = 8;
    else % If no BOG data available only plot RBR
        lg = legend(A(1),'RBR',Location='southeast');
        lg.FontSize = 8;
        subtitle(A(:),sbtitle)
    end
    
    hold(A,'off')
    %%
    % Set file save format options. Full 8.5 x 11 page, landscape.
    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
    
    datetime_sample = datestr(RSKprofiledatetime,'mmddyyyy_hhMM');
    % Save the figure as a PDF
    % Maybe save as a png as well for easy show and tell
    if exist("SiteID","var")
        filename = fullfile(folderName,[cruiseName,'_RBRupcast_',...
            num2str(profile),'_',char(SiteID),'_',datetime_sample,'.png']);
    else
        filename = fullfile(folderName,[cruiseName,'_RBRupcast_',...
            num2str(profile),'_',datetime_sample,'.png']);
    end
    saveas(gcf, filename);
% Want to add residuals plots
% Want to add optode gain plots
% Want to add chla gain plots
end