function plotProcessed(Processed, params, varargin)

%Plots output from Processed. Options for filtered traces, RMS rolling
%window amplitude traces, and spike raster or firing frequency plots.
%Holds to allow for changes in color scale, etc before saving

%% Plot traces

% Initialize a struct to store figure handles

t = 0:(params.downsampling/params.fs):((length(Processed{1})-1)*params.downsampling/params.fs);

if params.trace_plots == 1;

    Fig1 = struct();
    for i = 1:size(Processed,2)

        % Create a valid field name for the struct
        fieldName = matlab.lang.makeValidName(sprintf('fc_%d-%d', params.fc(i,:)));
        % Create figure
        Fig1.(fieldName) = figure;
        hold on;

        offset_rms = max(rms(Processed{i},2))*params.offset;
        % Plot each channel
        for ch = 1:height(params.Channels_main)
            % Offset the data for vertical stacking
            plot(t, Processed{i}(ch, :) + (height(params.Channels_main)- ch) * offset_rms, 'k');
        end
        % Customize plot appearance
        set(gca, 'YTick', [], 'XTick', []); % Remove axis ticks
        box off; % Remove box around the plot
        axis tight; % Fit axes to data
        % Add shaded regions with transparency
        yl = ylim;
        for i_2 = 1:size(params.shadedRegions, 1)
            fill([params.shadedRegions(i_2, 1), params.shadedRegions(i_2, 2), params.shadedRegions(i_2, 2), params.shadedRegions(i_2, 1)], ...
                [yl(1), yl(1), yl(2), yl(2)], [0.5 0.5 0.5], 'EdgeColor', 'none', 'FaceAlpha', params.transparency);
        end
        % Add scale bars
        xLimits = xlim;
        yLimits = ylim;
        % Define padding as a fraction of the axis range
        xPadding = 0.01 * range(xLimits); % as a % of x-axis range
        yPadding = 0.03 * range(yLimits); % as a % of y-axis range
        % Time scale bar
        plot([xLimits(2) - params.timeScale - xPadding, xLimits(2) - xPadding], ...
            [yLimits(1) - yPadding, yLimits(1) - yPadding], 'k', 'LineWidth', 2);
        text(xLimits(2) - params.timeScale / 2 - xPadding, yLimits(1) - 2 * yPadding, ...
            sprintf('%.1f s', params.timeScale), 'HorizontalAlignment', 'center', 'VerticalAlignment', 'top');
        % Amplitude scale bar
        plot([xLimits(2) - xPadding, xLimits(2) - xPadding], ...
            [yLimits(1) - yPadding, yLimits(1) + params.amplitudeScale - yPadding], 'k', 'LineWidth', 2);
        text(xLimits(2) + 0.5 * xPadding, yLimits(1) + params.amplitudeScale / 2 - yPadding, ...
            sprintf('%d µV', params.amplitudeScale), 'HorizontalAlignment', 'left', 'VerticalAlignment', 'middle');
        % Add channel labels
        yticks = (0:height(params.Channels_main)-1) * offset_rms; % Y positions for each channel
        yticklabels = arrayfun(@(ch) sprintf('Ch%d', ch), 1:height(params.Channels_main), 'UniformOutput', false); % Channel labels
        yticklabels=flip(yticklabels); %Needed for plot to correspond to the way channels are fed
        set(gca, 'YTick', yticks, 'YTickLabel', yticklabels, 'TickDir', 'out', 'YTickLabelRotation', 0);
        % Remove axis lines while keeping tick labels
        ax = gca;
        ax.XAxis.Axle.Visible = 'off'; % Remove x-axis line
        ax.YAxis.Axle.Visible = 'off'; % Remove y-axis line
        %Modify figure dimensions and save as vector
        % ylim([-offset_rms offset_rms*height(Channels_main)]); %Use in case the amplitude of some of the artefacts or similar is very large, though you'll loose the scale bars
        set(gcf,'Position', [0, 50, 850, height(params.Channels_main)*25+25]); %If you want the figure to have particular, consistent dimensions
        hold off;

        titleStr = sprintf('Ephys traces %d-%d Hz', params.fc(i,:));
        title(titleStr);
    end


    Fig11 = struct();
    for i = 1:size(Processed,2)

        % Create a valid field name for the struct
        fieldName = matlab.lang.makeValidName(sprintf('fc_%d-%d', params.fc(i,:)));
        % Create figure
        Fig11.(fieldName) = figure;

        plot(t,Processed{i}(height(Processed{i}),:),'k'); %Plot common avg reference channel

        % Customize plot appearance
        set(gca, 'YTick', [], 'XTick', []); % Remove axis ticks
        box off; % Remove box around the plot
        axis tight; % Fit axes to data
        % Add shaded regions with transparency
        yl = ylim;
        for i_2 = 1:size(params.shadedRegions, 1)
            fill([params.shadedRegions(i, 1), params.shadedRegions(i_2, 2), params.shadedRegions(i_2, 2), params.shadedRegions(i_2, 1)], ...
                [yl(1), yl(1), yl(2), yl(2)], [0.5 0.5 0.5], 'EdgeColor', 'none', 'FaceAlpha', params.transparency);
        end
        % Add scale bars
        xLimits = xlim;
        yLimits = ylim;
        % Remove axis lines while keeping tick labels
        ax = gca;
        ax.XAxis.Axle.Visible = 'off'; % Remove x-axis line
        ax.YAxis.Axle.Visible = 'off'; % Remove y-axis line

        %Modify figure dimensions and save as vector
        % ylim([-offset_rms offset_rms*height(Channels_main)]); %Use in case the amplitude of some of the artefacts or similar is very large, though you'll loose the scale bars
        set(gcf,'Position', [0, 50, 850, 100]); %If you want the figure to have particular, consistent dimensions
        hold off;

        titleStr = sprintf('Common Average Reference trace %d-%d Hz', params.fc(i,:));
        title(titleStr);
    end
end


%% Calculate RMS and firing rates

%In case values are needed for downstream calculations
if params.metric_processing ~= 1;
    Processed_RMSWind = [];
    Processed_FiringRate = [];

    % Save ephys traces here and end
    for i = 1:size(Processed,2)

        if exist('Fig1','var')
            titleStr = sprintf('Ephys traces %d-%d Hz', params.fc(i,:))
            fieldName = matlab.lang.makeValidName(sprintf('fc_%d-%d', params.fc(i,:)));
            saveFileName = fullfile(params.saveDirName,titleStr);
            figure(Fig1.(fieldName));
            saveas(Fig1.(fieldName),saveFileName)
            print(gcf,'-vector',saveFileName,'-dpng')
            %    print(gcf,'-vector',saveFileName,'-dsvg')
            close
        end


        if exist('Fig11', 'var')
            titleStr = sprintf('Common average ref trace %d-%d Hz', params.fc(i,:))
            fieldName = matlab.lang.makeValidName(sprintf('fc_%d-%d', params.fc(i,:)));
            saveFileName = fullfile(params.saveDirName,titleStr);
            figure(Fig11.(fieldName));
            saveas(Fig11.(fieldName),saveFileName)
            print(gcf,'-vector',saveFileName,'-dpng')
            %    print(gcf,'-vector',saveFileName,'-dsvg')
            close
        end

    end

    return
end

downsampling_metrics = params.downsampling_metrics/params.downsampling; %Since the order this is implemented would mean that the total downsampling is the product of both of these
t_small = downsample(t,downsampling_metrics); %Define time vector for metrics

fs = params.fs/params.downsampling;

%Amplitude (RMS rolling window) (normalised by median)

Processed_RMSWind{size(Processed,2)} = [];
for i = 1:size(Processed,2)

    Processed_RMSWind{i} = movmean(abs(Processed{i}),params.Window_length_RMS*(fs),2); %Window length defined in params
    Processed_RMSWind{i}(height(Processed_RMSWind{i}),:)=[]; %Delete last row corresponding to common average ref, since it isnt relevant here

    if params.RMS_normalisation == 1
        Processed_RMSWind{i} = Processed_RMSWind{i}-median(Processed_RMSWind{i},2);
    end

    Processed_RMSWind{i} = downsample(Processed_RMSWind{i}',downsampling_metrics);
    Processed_RMSWind{i} = Processed_RMSWind{i}';

end

%Firing rate (negative spikes followed by rolling window). Run only for
%high freq ranges (>800Hz), rest are kept empty

indices_firing = 1:1:size(params.fc,1);
indices_firing = indices_firing(params.fc(:,2) > 800);

Processed_FiringRate{size(Processed,2)} = [];
t_spikes{size(Processed,2)} = [];

for i = indices_firing

    n=height(Processed{i})-1; %Number of channels to analyse
    t_spikes{i}=zeros(n,length(t_small)); %This will contain spike locations

    xx=1;

    %Detection threshold is defined at the beginning (std_threshold_min). Min
    %distance between peaks is 5 ms.
    while xx<=n;
        if params.threshold_perChannel == 1; %Either use threshold based on that specific channel's std, or of all channels.
            [pks_n,locs_n]=findpeaks(-Processed{i}(xx,:),'MinPeakDistance',0.0005*fs,'MinPeakHeight',std(Processed{i}(xx,:))*params.std_threshold_min);
        else
            [pks_n,locs_n]=findpeaks(-Processed{i}(xx,:),'MinPeakDistance',0.0005*fs,'MinPeakHeight',std(Processed{i},1,"all")*params.std_threshold_min);
        end
        locs_n(pks_n>std(Processed{i}(xx,:))*params.std_threshold_max)=NaN;; %Eliminate too high peaks (assumed artefacts)
        locs_n=locs_n/(fs); %convert from time in samples to seconds, to match time line.
        yy=1;
        while yy<=length(locs_n) %Now go find each value spike location, one at a time
            [~,idx]=min(abs(t_small-locs_n(yy)));  %Find closest value in time line
            t_spikes{i}(xx,idx)=1; %Add value of 1 for spikes into number line of t_spikes
            yy=yy+1;
        end
        xx=xx+1;
    end

    %Rolling window for firing rate (no need to downsample since spike locs are
    %already cast on a 'downsampled' array
    %Step is skipped if Window_length=0 (i.e. to make a raster plot instead)

    if params.Window_length_Spike > 0
        Processed_FiringRate{i}=movmean(t_spikes{i},params.Window_length_Spike*(fs/downsampling_metrics),2); %Window length defined in params
    end
end


%% Plot RMS and firing rates

%Amplitude RMS

if or(params.metrics_plots == 1, params.metrics_plots == 3); %raw plots
    Fig2 = struct();
    for i = 1:size(Processed,2)

        % Create a valid field name for the struct
        fieldName = matlab.lang.makeValidName(sprintf('fc_%d-%d', params.fc(i,:)));
        % Create figure
        Fig2.(fieldName) = figure;
        hold on;

        offset_rms = max(rms(Processed_RMSWind{i},2))*params.offset/4;
        % Plot each channel
        for ch = 1:height(params.Channels_main)
            % Offset the data for vertical stacking
            plot(t_small, Processed_RMSWind{i}(ch, :) + (height(params.Channels_main)- ch) * offset_rms, 'k');
        end
        % Customize plot appearance
        set(gca, 'YTick', [], 'XTick', []); % Remove axis ticks
        box off; % Remove box around the plot
        axis tight; % Fit axes to data
        % Add shaded regions with transparency
        yl = ylim;
        for i_2 = 1:size(params.shadedRegions, 1)
            fill([params.shadedRegions(i, 1), params.shadedRegions(i_2, 2), params.shadedRegions(i_2, 2), params.shadedRegions(i_2, 1)], ...
                [yl(1), yl(1), yl(2), yl(2)], [0.5 0.5 0.5], 'EdgeColor', 'none', 'FaceAlpha', params.transparency);
        end
        % Add scale bars
        xLimits = xlim;
        yLimits = ylim;
        % Define padding as a fraction of the axis range
        xPadding = 0.01 * range(xLimits); % as a % of x-axis range
        yPadding = 0.03 * range(yLimits); % as a % of y-axis range
        % Time scale bar
        plot([xLimits(2) - params.timeScale - xPadding, xLimits(2) - xPadding], ...
            [yLimits(1) - yPadding, yLimits(1) - yPadding], 'k', 'LineWidth', 2);
        text(xLimits(2) - params.timeScale / 2 - xPadding, yLimits(1) - 2 * yPadding, ...
            sprintf('%.1f s', params.timeScale), 'HorizontalAlignment', 'center', 'VerticalAlignment', 'top');
        % Amplitude scale bar
        % plot([xLimits(2) - xPadding, xLimits(2) - xPadding], ...
        %     [yLimits(1) - yPadding, yLimits(1) + params.amplitudeScale - yPadding], 'k', 'LineWidth', 2);
        % text(xLimits(2) + 0.5 * xPadding, yLimits(1) + params.amplitudeScale / 2 - yPadding, ...
        %     sprintf('%d µV', params.amplitudeScale), 'HorizontalAlignment', 'left', 'VerticalAlignment', 'middle');
        % Add channel labels
        yticks = (0:height(params.Channels_main)-1) * offset_rms; % Y positions for each channel
        yticklabels = arrayfun(@(ch) sprintf('Ch%d', ch), 1:height(params.Channels_main), 'UniformOutput', false); % Channel labels
        yticklabels=flip(yticklabels); %Needed for plot to correspond to the way channels are fed
        set(gca, 'YTick', yticks, 'YTickLabel', yticklabels, 'TickDir', 'out', 'YTickLabelRotation', 0);
        % Remove axis lines while keeping tick labels
        ax = gca;
        ax.XAxis.Axle.Visible = 'off'; % Remove x-axis line
        ax.YAxis.Axle.Visible = 'off'; % Remove y-axis line
        %Modify figure dimensions and save as vector
        % ylim([-offset_rms offset_rms*height(Channels_main)]); %Use in case the amplitude of some of the artefacts or similar is very large, though you'll loose the scale bars
        set(gcf,'Position', [0, 50, 850, height(params.Channels_main)*25+25]); %If you want the figure to have particular, consistent dimensions
        hold off;



        titleStr = sprintf('RMS amplitude window %ds %d-%d Hz', [params.Window_length_RMS], params.fc(i,:));
        title(titleStr);

    end



    Fig3 = struct();
    for i = indices_firing
        %Firing rate
        % Create a valid field name for the struct
        fieldName = matlab.lang.makeValidName(sprintf('fc_%d-%d', params.fc(i,:)));

        if params.Window_length_Spike > 0 %to make a mov avg window plot
            Fig3.(fieldName) = figure;
            hold on;

            offset_rms = max(rms(Processed_FiringRate{i},2))*params.offset;
            % Plot each channel
            for ch = 1:height(params.Channels_main)
                % Offset the data for vertical stacking
                plot(t_small, Processed_FiringRate{i}(ch, :) + (height(params.Channels_main)- ch) * offset_rms, 'k');
            end
            % Customize plot appearance
            set(gca, 'YTick', [], 'XTick', []); % Remove axis ticks
            box off; % Remove box around the plot
            axis tight; % Fit axes to data
            % Add shaded regions with transparency
            yl = ylim;
            for i_2 = 1:size(params.shadedRegions, 1)
                fill([params.shadedRegions(i, 1), params.shadedRegions(i_2, 2), params.shadedRegions(i_2, 2), params.shadedRegions(i_2, 1)], ...
                    [yl(1), yl(1), yl(2), yl(2)], [0.5 0.5 0.5], 'EdgeColor', 'none', 'FaceAlpha', params.transparency);
            end
            % Add scale bars
            xLimits = xlim;
            yLimits = ylim;
            % Define padding as a fraction of the axis range
            xPadding = 0.01 * range(xLimits); % as a % of x-axis range
            yPadding = 0.03 * range(yLimits); % as a % of y-axis range
            % Time scale bar
            plot([xLimits(2) - params.timeScale - xPadding, xLimits(2) - xPadding], ...
                [yLimits(1) - yPadding, yLimits(1) - yPadding], 'k', 'LineWidth', 2);
            text(xLimits(2) - params.timeScale / 2 - xPadding, yLimits(1) - 2 * yPadding, ...
                sprintf('%.1f s', params.timeScale), 'HorizontalAlignment', 'center', 'VerticalAlignment', 'top');
            % % Amplitude scale bar
            % plot([xLimits(2) - xPadding, xLimits(2) - xPadding], ...
            %     [yLimits(1) - yPadding, yLimits(1) + params.amplitudeScale - yPadding], 'k', 'LineWidth', 2);
            % text(xLimits(2) + 0.5 * xPadding, yLimits(1) + params.amplitudeScale / 2 - yPadding, ...
            %     sprintf('%d µV', params.amplitudeScale), 'HorizontalAlignment', 'left', 'VerticalAlignment', 'middle');
            % Add channel labels
            yticks = (0:height(params.Channels_main)-1) * offset_rms; % Y positions for each channel
            yticklabels = arrayfun(@(ch) sprintf('Ch%d', ch), 1:height(params.Channels_main), 'UniformOutput', false); % Channel labels
            yticklabels=flip(yticklabels); %Needed for plot to correspond to the way channels are fed
            set(gca, 'YTick', yticks, 'YTickLabel', yticklabels, 'TickDir', 'out', 'YTickLabelRotation', 0);
            % Remove axis lines while keeping tick labels
            ax = gca;
            ax.XAxis.Axle.Visible = 'off'; % Remove x-axis line
            ax.YAxis.Axle.Visible = 'off'; % Remove y-axis line
            %Modify figure dimensions and save as vector
            % ylim([-offset_rms offset_rms*height(Channels_main)]); %Use in case the amplitude of some of the artefacts or similar is very large, though you'll loose the scale bars
            set(gcf,'Position', [0, 50, 850, height(params.Channels_main)*25+25]); %If you want the figure to have particular, consistent dimensions
            hold off;

            titleStr = sprintf('Spike rate window %ds %d-%d Hz', [params.Window_length_Spike], params.fc(i,:));
            title(titleStr);


        else %to make a raster plot
            Fig3.(fieldName) = figure;
            hold on;
            offset_raster = 0.2;
            % Plot each channel
            for ch = 1:height(params.Channels_main)
                % Offset the data for vertical stacking
                plot(t_small, t_spikes(ch, :) + (height(params.Channels_main)- ch) * offset_raster, 'k');
            end
            % Customize plot appearance
            set(gca, 'YTick', [], 'XTick', []); % Remove axis ticks
            box off; % Remove box around the plot
            axis tight; % Fit axes to data
            % Add shaded regions with transparency
            yl = ylim;
            for i_2 = 1:size(params.shadedRegions, 1)
                fill([params.shadedRegions(i_2, 1), params.shadedRegions(i_2, 2), params.shadedRegions(i_2, 2), params.shadedRegions(i_2, 1)], ...
                    [yl(1), yl(1), yl(2), yl(2)], [0.5 0.5 0.5], 'EdgeColor', 'none', 'FaceAlpha', params.transparency);
            end
            % Add scale bars
            xLimits = xlim;
            yLimits = ylim;
            % Define padding as a fraction of the axis range
            xPadding = 0.01 * range(xLimits); % as a % of x-axis range
            yPadding = 0.03 * range(yLimits); % as a % of y-axis range
            % Time scale bar
            plot([xLimits(2) - params.timeScale - xPadding, xLimits(2) - xPadding], ...
                [yLimits(1) - yPadding, yLimits(1) - yPadding], 'k', 'LineWidth', 2);
            text(xLimits(2) - params.timeScale / 2 - xPadding, yLimits(1) - 2 * yPadding, ...
                sprintf('%.1f s', params.timeScale), 'HorizontalAlignment', 'center', 'VerticalAlignment', 'top');
            % Amplitude scale bar
            plot([xLimits(2) - xPadding, xLimits(2) - xPadding], ...
                [yLimits(1) - yPadding, yLimits(1) + params.amplitudeScale - yPadding], 'k', 'LineWidth', 2);
            text(xLimits(2) + 0.5 * xPadding, yLimits(1) + params.amplitudeScale / 2 - yPadding, ...
                sprintf('%d µV', params.amplitudeScale), 'HorizontalAlignment', 'left', 'VerticalAlignment', 'middle');
            % Add channel labels
            yticks = (0:height(params.Channels_main)-1) * offset_raster; % Y positions for each channel
            yticklabels = arrayfun(@(ch) sprintf('Ch%d', ch), 1:height(params.Channels_main), 'UniformOutput', false); % Channel labels
            yticklabels=flip(yticklabels); %Needed for plot to correspond to the way channels are fed
            set(gca, 'YTick', yticks, 'YTickLabel', yticklabels, 'TickDir', 'out', 'YTickLabelRotation', 0);
            % Remove axis lines while keeping tick labels
            ax = gca;
            ax.XAxis.Axle.Visible = 'off'; % Remove x-axis line
            ax.YAxis.Axle.Visible = 'off'; % Remove y-axis line
            %Modify figure dimensions and save as vector
            % ylim([-offset_rms offset_rms*height(Channels_main)]); %Use in case the amplitude of some of the artefacts or similar is very large, though you'll loose the scale bars
            set(gcf,'Position', [0, 50, 850, height(params.Channels_main)*25+25]); %If you want the figure to have particular, consistent dimensions
            hold off;


            titleStr = sprintf('Spike rate raster %d-%d Hz', params.fc(i,:));
            title(titleStr);
        end
    end
end

%% Heatmap plots

if or(params.metrics_plots == 2, params.metrics_plots == 3); %Heatmap plots

    Processed_RMSWind_heatmap{size(Processed,2)} = [];
    Fig4 = struct();

    for i = 1:size(Processed,2)

        % Create a valid field name for the struct
        fieldName = matlab.lang.makeValidName(sprintf('fc_%d-%d', params.fc(i,:)));
        % Create figure
        Fig4.(fieldName) = figure; %Amplitude
        hold on;

        for ch = 1:height(params.Channels_main) %Quickly make a matrix of only channels to plot in heatmap
            Processed_RMSWind_heatmap{i}(ch,:) = Processed_RMSWind{i}(ch,:);
        end

        Processed_RMSWind_heatmap{i} = [Processed_RMSWind_heatmap{i} ; nan(1,length(Processed_RMSWind_heatmap{i}))]; %Need to add another row for heatmap plot to display correctly (fencepost bug)

        s=pcolor(t_small,flip(1:height(Processed_RMSWind_heatmap{i})),Processed_RMSWind_heatmap{i});
        set(s, 'EdgeColor', 'none');
        titleStr = sprintf('RMS amplitude window %ds %d-%d Hz', [params.Window_length_RMS], params.fc(i,:));
        title(titleStr);
        xlabel('time (s)')
        ylabel('Nerve cuff channel')
        a=colorbar;
        ylabel(a,'RMS window (uV)');
        ylim([1 height(Processed{i})])
        yticklabels = arrayfun(@(ch) sprintf('Ch%d', ch), 1:2:height(params.Channels_main), 'UniformOutput', false); %assuming labels are presented in sets of 2 chs, otherwise this needs changing
        yticklabels=[{''},yticklabels]; %Add an empty label for the NaN vector
        set(gca, 'YTickLabel', flip(yticklabels)); %Flip y ticks. Channels plotting order already reversed in pcolor
    end


    if params.Window_length_Spike > 0

        Processed_FiringRate_heatmap{size(Processed,2)} = [];
        Fig5 = struct();

        for i = indices_firing

            % Create a valid field name for the struct
            fieldName = matlab.lang.makeValidName(sprintf('fc_%d-%d', params.fc(i,:)));
            % Create figure
            Fig5.(fieldName) = figure; %Amplitude
            hold on;

            for ch = 1:height(params.Channels_main) %Quickly make a matrix of only channels to plot in heatmap
                Processed_FiringRate_heatmap{i}(ch,:) = Processed_FiringRate{i}(ch,:);
            end

            Processed_FiringRate_heatmap{i}= [Processed_FiringRate_heatmap{i};nan(1,length(Processed_FiringRate_heatmap{i}))]; %Need to add another row for heatmap plot to display correctly (fencepost bug)

            s=pcolor(t_small,flip(1:height(Processed_FiringRate_heatmap{i})),Processed_FiringRate_heatmap{i});
            set(s, 'EdgeColor', 'none');
            titleStr = sprintf('Spike rate window %ds %d-%d Hz', [params.Window_length_Spike], params.fc(i,:));
            title(titleStr);
            xlabel('time (s)')
            ylabel('Nerve cuff channel')
            a=colorbar;
            ylabel(a,'Spike rate (t^-^1)');
            ylim([1 height(Processed{i})])
            yticklabels = arrayfun(@(ch) sprintf('Ch%d', ch), 1:2:height(params.Channels_main), 'UniformOutput', false); %assuming labels are presented in sets of 2 chs, otherwise this needs changing
            yticklabels=[{''},yticklabels]; %Add an empty label for the NaN vector
            set(gca, 'YTickLabel', flip(yticklabels)); %Flip y ticks. Channels plotting order already reversed in pcolor
        end
    end
end

%% Option to hold to allow for graphics changes, then save

disp('Saving...') %Opportunity to stop and recolor using caxis or similar

if exist('Processed_RMSWind','var')
    saveFileName = fullfile(params.saveDirName,'Processed_RMS');
    save(saveFileName,'Processed_RMSWind');
end

if exist('t_small','var')
    saveFileName = fullfile(params.saveDirName,'time');
    save(saveFileName,'t_small');
end

if exist('Processed_FiringRate','var')
    saveFileName = fullfile(params.saveDirName,'Processed_FiringRate');
    save(saveFileName,'Processed_FiringRate');
end

for i = 1:size(Processed,2)

    if exist('Fig1','var')
        titleStr = sprintf('Ephys traces %d-%d Hz', params.fc(i,:));
        fieldName = matlab.lang.makeValidName(sprintf('fc_%d-%d', params.fc(i,:)));
        saveFileName = fullfile(params.saveDirName,titleStr);
        figure(Fig1.(fieldName));
             %saveas(Fig1.(fieldName),saveFileName)
        print(gcf,'-vector',saveFileName,'-dpng')
        %    print(gcf,'-vector',saveFileName,'-dsvg')
        close
    end
%saveFileNameP = fullfile(params.saveDirName,'Processed.mat');
%save(saveFileNameP,'Processed');

    if exist('Fig11', 'var')
        titleStr = sprintf('Common average ref trace %d-%d Hz', params.fc(i,:));
        fieldName = matlab.lang.makeValidName(sprintf('fc_%d-%d', params.fc(i,:)));
        saveFileName = fullfile(params.saveDirName,titleStr);
        figure(Fig11.(fieldName));
        %   saveas(Fig11.(fieldName),saveFileName)
        print(gcf,'-vector',saveFileName,'-dpng')
        %    print(gcf,'-vector',saveFileName,'-dsvg')
        close
    end


    if exist('Fig2', 'var')
        titleStr = sprintf('RMS amplitude %.0f-%.0f Hz', params.fc(i,:));
        fieldName = matlab.lang.makeValidName(sprintf('fc_%d-%d', params.fc(i,:)));
        saveFileName = fullfile(params.saveDirName,titleStr);
        figure(Fig2.(fieldName));
        saveas(Fig2.(fieldName),saveFileName)
        print(gcf,'-vector',saveFileName,'-dpng')
        %    print(gcf,'-vector',saveFileName,'-dsvg')
        close
    end


    if exist('Fig4', 'var')
        titleStr = sprintf('RMS amplitude heatmap %.0f-%.0f Hz', params.fc(i,:));
        fieldName = matlab.lang.makeValidName(sprintf('fc_%d-%d', params.fc(i,:)));
        saveFileName = fullfile(params.saveDirName,titleStr);
        figure(Fig4.(fieldName));
        saveas(Fig4.(fieldName),saveFileName)
        print(gcf,'-vector',saveFileName,'-dpng')
        close
    end
end

for i = indices_firing

    if exist('Fig3', 'var')
        titleStr = sprintf('Spike rate %.0f-%.0f Hz', params.fc(i,:));
        fieldName = matlab.lang.makeValidName(sprintf('fc_%d-%d', params.fc(i,:)));
        saveFileName = fullfile(params.saveDirName,titleStr);
        figure(Fig3.(fieldName));
        saveas(Fig3.(fieldName),saveFileName)
        print(gcf,'-vector',saveFileName,'-dpng')
        %    print(gcf,'-vector',saveFileName,'-dsvg')
        close
    end


    if exist('Fig5', 'var')
        titleStr = sprintf('Spike rate heatmap %ds %d-%d Hz', params.fc(i,:));
        fieldName = matlab.lang.makeValidName(sprintf('fc_%d-%d', params.fc(i,:)));
        saveFileName = fullfile(params.saveDirName,titleStr);
        figure(Fig5.(fieldName));
        saveas(Fig5.(fieldName),saveFileName)
        print(gcf,'-vector',saveFileName,'-dpng')
        close
    end
end


%% Plot and save other ring of electrodes if provided

if length(varargin) == 1

    Processed_second = varargin{1};

    if params.trace_plots == 1;

        Fig1_second = struct();

        % Create a valid field name for the struct
        fieldName = matlab.lang.makeValidName(sprintf('fc_%d-%d', params.fc(i,:)));
        % Create figure
        Fig1_second.(fieldName) = figure;
        hold on;

        offset_rms = max(rms(Processed_second,2))*params.offset;
        % Plot each channel
        for ch = 1:height(params.Channels_main_second)
            % Offset the data for vertical stacking
            plot(t, Processed_second(ch, :) + (height(params.Channels_main_second)- ch) * offset_rms, 'k');
        end
        % Customize plot appearance
        set(gca, 'YTick', [], 'XTick', []); % Remove axis ticks
        box off; % Remove box around the plot
        axis tight; % Fit axes to data
        % Add shaded regions with transparency
        yl = ylim;
        for i_2 = 1:size(params.shadedRegions, 1)
            fill([params.shadedRegions(i_2, 1), params.shadedRegions(i_2, 2), params.shadedRegions(i_2, 2), params.shadedRegions(i_2, 1)], ...
                [yl(1), yl(1), yl(2), yl(2)], [0.5 0.5 0.5], 'EdgeColor', 'none', 'FaceAlpha', params.transparency);
        end
        % Add scale bars
        xLimits = xlim;
        yLimits = ylim;
        % Define padding as a fraction of the axis range
        xPadding = 0.01 * range(xLimits); % as a % of x-axis range
        yPadding = 0.03 * range(yLimits); % as a % of y-axis range
        % Time scale bar
        plot([xLimits(2) - params.timeScale - xPadding, xLimits(2) - xPadding], ...
            [yLimits(1) - yPadding, yLimits(1) - yPadding], 'k', 'LineWidth', 2);
        text(xLimits(2) - params.timeScale / 2 - xPadding, yLimits(1) - 2 * yPadding, ...
            sprintf('%.1f s', params.timeScale), 'HorizontalAlignment', 'center', 'VerticalAlignment', 'top');
        % Amplitude scale bar
        plot([xLimits(2) - xPadding, xLimits(2) - xPadding], ...
            [yLimits(1) - yPadding, yLimits(1) + params.amplitudeScale - yPadding], 'k', 'LineWidth', 2);
        text(xLimits(2) + 0.5 * xPadding, yLimits(1) + params.amplitudeScale / 2 - yPadding, ...
            sprintf('%d µV', params.amplitudeScale), 'HorizontalAlignment', 'left', 'VerticalAlignment', 'middle');
        % Add channel labels
        yticks = (0:height(params.Channels_main_second)-1) * offset_rms; % Y positions for each channel
        yticklabels = arrayfun(@(ch) sprintf('Ch%d', ch), 1:height(params.Channels_main_second), 'UniformOutput', false); % Channel labels
        yticklabels=flip(yticklabels); %Needed for plot to correspond to the way channels are fed
        set(gca, 'YTick', yticks, 'YTickLabel', yticklabels, 'TickDir', 'out', 'YTickLabelRotation', 0);
        % Remove axis lines while keeping tick labels
        ax = gca;
        ax.XAxis.Axle.Visible = 'off'; % Remove x-axis line
        ax.YAxis.Axle.Visible = 'off'; % Remove y-axis line
        %Modify figure dimensions and save as vector
        % ylim([-offset_rms offset_rms*height(Channels_main)]); %Use in case the amplitude of some of the artefacts or similar is very large, though you'll loose the scale bars
        set(gcf,'Position', [0, 50, 850, height(params.Channels_main_second)*25+25]); %If you want the figure to have particular, consistent dimensions
        hold off;

        titleStr = sprintf('Ephys traces second ring %d-%d Hz', params.fc(i,:));
        title(titleStr);



        Fig11_second = struct();

        % Create a valid field name for the struct
        fieldName = matlab.lang.makeValidName(sprintf('fc_%d-%d', params.fc(i,:)));
        % Create figure
        Fig11_second.(fieldName) = figure;

        plot(t,Processed_second(height(Processed_second),:),'k'); %Plot common avg reference channel

        % Customize plot appearance
        set(gca, 'YTick', [], 'XTick', []); % Remove axis ticks
        box off; % Remove box around the plot
        axis tight; % Fit axes to data
        % Add shaded regions with transparency
        yl = ylim;
        for i_2 = 1:size(params.shadedRegions, 1)
            fill([params.shadedRegions(i, 1), params.shadedRegions(i_2, 2), params.shadedRegions(i_2, 2), params.shadedRegions(i_2, 1)], ...
                [yl(1), yl(1), yl(2), yl(2)], [0.5 0.5 0.5], 'EdgeColor', 'none', 'FaceAlpha', params.transparency);
        end
        % Add scale bars
        xLimits = xlim;
        yLimits = ylim;
        % Remove axis lines while keeping tick labels
        ax = gca;
        ax.XAxis.Axle.Visible = 'off'; % Remove x-axis line
        ax.YAxis.Axle.Visible = 'off'; % Remove y-axis line

        %Modify figure dimensions and save as vector
        % ylim([-offset_rms offset_rms*height(Channels_main)]); %Use in case the amplitude of some of the artefacts or similar is very large, though you'll loose the scale bars
        set(gcf,'Position', [0, 50, 850, 100]); %If you want the figure to have particular, consistent dimensions
        hold off;

        titleStr = sprintf('Common Average Reference trace second ring %d-%d Hz', params.fc(i,:));
        title(titleStr);

    end

    % Save

    if exist('Fig1_second','var')
        titleStr = sprintf('Ephys traces second ring %d-%d Hz', params.fc(i,:));
        fieldName = matlab.lang.makeValidName(sprintf('fc_%d-%d', params.fc(i,:)));
        saveFileName = fullfile(params.saveDirName,titleStr);
        figure(Fig1_second.(fieldName));
        %   saveas(Fig1.(fieldName),saveFileName)
        print(gcf,'-vector',saveFileName,'-dpng')
        %    print(gcf,'-vector',saveFileName,'-dsvg')
        close
    end


    if exist('Fig11_second', 'var')
        titleStr = sprintf('Common average ref trace second ring %d-%d Hz', params.fc(i,:));
        fieldName = matlab.lang.makeValidName(sprintf('fc_%d-%d', params.fc(i,:)));
        saveFileName = fullfile(params.saveDirName,titleStr);
        figure(Fig11_second.(fieldName));
        %   saveas(Fig11.(fieldName),saveFileName)
        print(gcf,'-vector',saveFileName,'-dpng')
        %    print(gcf,'-vector',saveFileName,'-dsvg')
        close
    end

end


end

