fileloadpath = ['\\atlas.shore.mbari.org\projectlibrary\' ...
    '901805_Coastal_Biogeochemical_Sensing\Spray_Data\24A03401\' ...
    '\QC\24A03401_calibrated.mat'];
filesavepath = 'C:\Users\bwerb\Documents\dep_24A03401\QCPlots';
load(fileloadpath,'s');
n = length(s.sdn);
xvars = {'tc','psal','opt','doxy','par'};
yvar = {'pres'};
xlabels = {'Temperature (^oC)','Salinity (PSU)',...
    'Fluoresence', 'Doxy (\mumol/kg)', 'PAR'};
xlims = [3.5 14; 33.5 34.5; 0 2; 0 300; 0 100];

for profile = 1:n 
% for profile = 40
    figure(1)
    clf
    tl = tiledlayout(2,3);
    title(tl,['QC plots 24A03401, upcast profile: ', num2str(profile)])


    [M, Istart] = max(s.pres(:,profile)); % find max pres
    [Mi, Iend] = min(abs(0 - s.pres(:,profile))); % find surface sample
    upcastidx = (Istart:Iend)'; % make upcast idx
    % upcastidx = diff(s.pres(:,profile));
    % upcastidx = [upcastidx; 1]; %#ok<AGROW>
    % % upcastidx = upcastidx < 0; % downcast
    % upcastidx = upcastidx > 0 & s.pres(:,profile) > 0; % think this is upcast. Need a way to remove weird last data points


    for i = 1:5
        nexttile(tl)
        if isempty(upcastidx)
            plot(s.(xvars{i})(:,profile),s.(yvar{1})(:,profile),'.',MarkerSize=2)
        elseif ~isempty(upcastidx)
            plot(s.(xvars{i})(upcastidx,profile),s.(yvar{1})(upcastidx,profile),'.',MarkerSize=2)
        end
        xlabel(xlabels{i})
        grid on
        set(gca,'Ydir','reverse')
        xlim(xlims(i,:))

    end
    
    % Create the filename for saving the figure
    filename = fullfile(filesavepath, sprintf('QCPlot_profile_upcast_%d.png', profile));
    
    % Save the figure as a PNG file
    saveas(gcf, filename)
end