function plotTwoModeGaussianFitsOnRawASD(fitResults, rawCurves, nRows, nCols, varargin)
%% plotTwoModeGaussianFitsOnRawASD
% Author:       Karthik
% Date:         2025-10-16
% Version:      1.0
%
% Description:
%   Plots raw radial spectral curves with their two-Gaussian fits in a
%   compact, paginated layout. Each page shows up to nRows × nCols subplots.
%
% Inputs:
%   fitResults - struct array from fitTwoGaussianCurvesToRadialSpectralDistribution
%   rawCurves  - struct array with fields:
%                   .x - raw normalized amplitudes
%                   .k - corresponding k_rho values
%   nRows      - number of subplot rows per page (default: 8)
%   nCols      - number of subplot columns per page (default: 12)
%   varargin   - name-value pairs:
%                   'FontName', 'FontSize', 'SkipLivePlot', 'SkipSaveFigures',
%                   'SaveDirectory', 'RepsPerPage'

    % --- Parse optional name-value pairs ---
    p = inputParser;
    addParameter(p, 'FontName', 'Arial', @ischar);
    addParameter(p, 'FontSize', 12, @isnumeric);
    addParameter(p, 'SkipLivePlot', false, @islogical);
    addParameter(p, 'SkipSaveFigures', true, @islogical);
    addParameter(p, 'SaveDirectory', pwd, @ischar);
    addParameter(p, 'RepsPerPage', [], @isnumeric); % optional override of nRows*nCols
    parse(p, varargin{:});
    opts = p.Results;

    % --- Default subplot grid if not provided ---
    if nargin < 3 || isempty(nRows), nRows = 8; end
    if nargin < 4 || isempty(nCols), nCols = 12; end

    plotsPerPage = nRows * nCols;
    if ~isempty(opts.RepsPerPage)
        plotsPerPage = opts.RepsPerPage;
    end

    Ncurves = numel(rawCurves);
    numPages = ceil(Ncurves / plotsPerPage);

    % --- Setup save directory if needed ---
    if ~opts.SkipSaveFigures
        saveFolder = fullfile(opts.SaveDirectory, 'Results', 'SavedFigures', 'TwoGaussianFits');
        if ~exist(saveFolder, 'dir')
            mkdir(saveFolder);
        end
    end

    for pageIdx = 1:numPages
        repStart = (pageIdx-1)*plotsPerPage + 1;
        repEnd   = min(pageIdx*plotsPerPage, Ncurves);
        repSubset = repStart:repEnd;
        N_rows = numel(repSubset);

        % --- Create figure ---
        if ~opts.SkipLivePlot
            fig = figure('Color', 'w', 'Position', [50 50 1600 900]);
        else
            fig = figure('Color', 'w', 'Position', [50 50 1600 900], 'Visible', 'off');
        end

        t = tiledlayout(fig, ceil(N_rows/nCols), nCols, 'TileSpacing', 'compact', 'Padding', 'compact');
        title(t, sprintf('Two-Gaussian fits | Page %d/%d', pageIdx, numPages), ...
            'FontSize', opts.FontSize + 2, 'FontWeight', 'bold', 'FontName', opts.FontName);

        for r = 1:N_rows
            k = repSubset(r);
            nexttile;
            hold on; grid on; box on;

            % --- Plot raw curve ---
            if isfield(rawCurves, 'x') && isfield(rawCurves, 'theta') && ...
               ~isempty(rawCurves(k).x) && all(isfinite(rawCurves(k).x))
                plot(rawCurves(k).theta, rawCurves(k).x, 'k.-', ...
                    'LineWidth', 1, 'DisplayName', 'Raw data');
            end

            % --- Overlay fit if valid ---
            if k <= numel(fitResults)
                fit = fitResults(k);
                if isfield(fit, 'isValid') && ~isempty(fit.isValid) && fit.isValid && ...
                   isfield(fit, 'thetaFine') && isfield(fit, 'yFit') && ...
                   ~isempty(fit.thetaFine) && all(isfinite(fit.yFit))
                    plot(fit.thetaFine, fit.yFit, 'r-', ...
                        'LineWidth', 1.2, 'DisplayName', 'Two-Gaussian fit');
                end
            end
            
            % --- Labels and title ---
            xlabel('\theta (rad)', 'FontSize', opts.FontSize);
            ylabel('N. A.', 'FontSize', opts.FontSize);
            
            % Build title with residuals if available
            if k <= numel(fitResults) && isfield(fitResults(k), 'residual') && isfield(fitResults(k), 'maxAbs')
                resRMS = fitResults(k).residual;
                resMax = fitResults(k).maxAbs;
                titleStr = sprintf('%d | R_{RMS}=%.3g | R_{Max}=%.3g', k, resRMS, resMax);
            else
                titleStr = sprintf('Shot %d', k);
            end
            
            title(titleStr, 'FontSize', opts.FontSize - 2, 'Interpreter', 'tex');

            hold off;
        end

        % --- Render live plot ---
        if ~opts.SkipLivePlot
            drawnow;
        end

        % --- Save figure ---
        if ~opts.SkipSaveFigures
            saveFileName = sprintf('TwoGaussianFits_page_%02d.png', pageIdx);
            if exist('Plotter', 'class')
                Plotter.saveFigure(fig, ...
                    'SaveFileName', saveFileName, ...
                    'SaveDirectory', saveFolder, ...
                    'SkipSaveFigures', opts.SkipSaveFigures);
            else
                saveas(fig, fullfile(saveFolder, saveFileName));
            end
        end

        % --- Close invisible figure to free memory ---
        if opts.SkipLivePlot
            close(fig);
        end
    end
end
