function plotSpectralCurvesRecentered(results, scan_reference_values, varargin)
%% plotSpectralCurves
% Author:       Karthik
% Date:         2025-10-01
% Version:      1.0
%
% Description:
%   Plot raw spectral curves with mean, SEM, and highlights
%   Preprocess: shifts each curve so its first peak is at zero (no wrap-around)
%
% Inputs:
%   S_theta_all            - 1x(N_reps*N_params) cell array of curves
%   theta_vals             - vector of theta values (radians)
%   scan_reference_values  - vector of unique scan parameters
%
% Optional name-value pairs:
%   'Title'            - Figure title (default: 'Spectral Curves')
%   'XLabel'           - Label for x-axis (default: '\theta / \pi')
%   'YLabel'           - Label for y-axis (default: 'S(\theta)')
%   'FontName'         - Font name (default: 'Arial')
%   'FontSize'         - Font size (default: 14)
%   'FigNum'           - Figure number (default: [])
%   'SkipSaveFigures'  - Logical flag to skip saving (default: false)
%   'SaveFileName'     - Name of figure file (default: 'SpectralCurves.fig')
%   'SaveDirectory'    - Directory to save figure (default: pwd)
%   'TileTitlePrefix'  - Prefix for tile titles (default: 'Scan Parameter')
%   'TileTitleSuffix'  - Suffix for tile titles (default: '')
%   'HighlightEvery'   - Highlight every Nth repetition (default: 10)
%
% Notes:
%   Automatically computes number of repetitions from S_theta_all length and scan_reference_values.

    % --- Parse name-value pairs ---
    p = inputParser;
    addParameter(p, 'Title', 'Spectral Curves', @(x) ischar(x) || isstring(x));
    addParameter(p, 'XLabel', '\theta / \pi', @(x) ischar(x) || isstring(x));
    addParameter(p, 'YLabel', 'S(\theta)', @(x) ischar(x) || isstring(x));
    addParameter(p, 'FontName', 'Arial', @ischar);
    addParameter(p, 'FontSize', 14, @isnumeric);
    addParameter(p, 'FigNum', [], @(x) isempty(x) || (isnumeric(x) && isscalar(x)));
    addParameter(p, 'SkipSaveFigures', false, @islogical);
    addParameter(p, 'SaveFileName', 'SpectralCurves.fig', @ischar);
    addParameter(p, 'SaveDirectory', pwd, @ischar);
    addParameter(p, 'TileTitlePrefix', 'Scan Parameter', @(x) ischar(x) || isstring(x));
    addParameter(p, 'TileTitleSuffix', '', @(x) ischar(x) || isstring(x));
    addParameter(p, 'HighlightEvery', 10, @(x) isnumeric(x) && isscalar(x) && x>=1);
    parse(p, varargin{:});
    opts = p.Results;

    % --- Determine number of scan parameters and repetitions ---
    N_params  = numel(scan_reference_values);
    
    % --- Create figure ---
    if isempty(opts.FigNum), fig = figure; else, fig = figure(opts.FigNum); end
    clf(fig);
    set(fig,'Color','w','Position',[100 100 950 750]);
    t = tiledlayout('TileSpacing','compact','Padding','compact');
    title(t, opts.Title, 'FontName', opts.FontName, 'FontSize', opts.FontSize+2);

    % --- Loop over scan parameters ---
    for i = 1:N_params
        ax = nexttile; hold(ax,'on');

        G = results.curves{i}; % [N_reps × Npoints]

        % --- Plot all repetitions in light grey ---
        plot(ax, results.x_values, G', 'Color', [0.7 0.7 0.7, 0.5]);

        % --- Highlight every Nth repetition ---
        idx = opts.HighlightEvery:opts.HighlightEvery:size(G,1);
        for j = idx
            plot(ax, results.x_values, G(j,:), 'Color', [0.3 0.3 0.3, 1], 'LineWidth', 1.5);
        end

        % --- Mean + SEM shading ---
        mu = results.curves_mean{i};
        se = results.curves_error{i};
        fill(ax, [results.x_values fliplr(results.x_values)], [mu-se fliplr(mu+se)], ...
            [0.2 0.4 0.8], 'FaceAlpha',0.2, 'EdgeColor','none');

        % --- Mean curve ---
        plot(ax, results.x_values, mu, 'b-', 'LineWidth', 2);
        
        % --- Vertical reference lines at pi/3 and 2pi/3 ---
        xlines = [1/3 2/3];
        for xl = xlines
            xline(ax, xl, 'k--', 'LineWidth', 1.5, 'Alpha', 0.5);
        end
        
        % --- Axes formatting ---
        grid(ax,'on');
        xlabel(ax, opts.XLabel, 'FontName', opts.FontName, 'FontSize', opts.FontSize);
        ylabel(ax, opts.YLabel, 'FontName', opts.FontName, 'FontSize', opts.FontSize);
        title(ax, sprintf('%s=%.3g%s', opts.TileTitlePrefix, results.scan_reference_values(i), opts.TileTitleSuffix), ...
                'FontName', opts.FontName, 'FontSize', opts.FontSize);
        set(ax, 'FontName', opts.FontName, 'FontSize', opts.FontSize);
    end

    % --- Save figure ---
    if ~opts.SkipSaveFigures
        if ~exist(opts.SaveDirectory,'dir'), mkdir(opts.SaveDirectory); end
        savefig(fig, fullfile(opts.SaveDirectory, opts.SaveFileName));
    end
end
