fileloadpath = ['\\atlas.shore.mbari.org\projectlibrary\' ...
    '901805_Coastal_Biogeochemical_Sensing\Spray_Data\24802901\' ...
    '\QC\24802901_QC.mat'];
filesavepath = 'C:\Users\bwerb\Documents\dep_24802901\QCPlots_QC_upcasts\prof_Ik';
load(fileloadpath,'s');
n = length(s.sdn);
yvars = {'tc','psal','opt','pHin','doxy','par'};
xvar = {'pres'};
ylabels = {'Temperature (^oC)','Salinity (PSU)',...
    'Fluoresence', 'pHin', 'Doxy (\mumol/kg)', 'PAR'};
ylimsleft = [3.5 14; 33.5 34.5; 0 2; 7.5 8; 0 300; 0 100];
ylimsright = [-100 100];
for profile = 1:n 
% for profile = 40
    figure(1)
    clf
    tl = tiledlayout(2,3,TileSpacing="compact");
    title(tl,['QC plots 24802901, upcast profile, Ik 5pt mn: ', 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:6
        nexttile(tl)
        if isempty(upcastidx)
            plot(s.(xvar{1})(:,profile),s.(yvars{i})(:,profile),'.',MarkerSize=2)
        elseif ~isempty(upcastidx)
            plot(s.(xvar{1})(upcastidx,profile),s.(yvars{i})(upcastidx,profile),'.',MarkerSize=2)
        end
        ylabel(ylabels{i})
        grid on
        set(gca,'Ydir','reverse')
        ylim(ylimsleft(i,:))
        hold on;
        yyaxis right
        if isempty(upcastidx)
            plot(s.(xvar{1})(:,profile),movmean(s.Ik(:,profile),5),'-',MarkerSize=2)
        elseif ~isempty(upcastidx)
            plot(s.(xvar{1})(upcastidx,profile),movmean(s.Ik(upcastidx,profile),5),'-',MarkerSize=2)
        end
        ylim(ylimsright)
        ylabel('Ik')
    end
    
    % Create the filename for saving the figure
    filename = fullfile(filesavepath, sprintf('QCPlot_profile_upcast_Ik_%d.png', profile));
    
    % Save the figure as a PNG file
    set(gcf, 'Position', [100, 100, 1200, 800]);  % Set figure size for full-page
    set(gcf, 'PaperPositionMode', 'auto');        % Set paper position mode to auto
    saveas(gcf, filename)
end