%% --- User chooses which dataset to load ---
datasetIdx                = 1;   % <-- change this to 1, 2, 3, ...
datasetName               = sprintf('Dataset_%d', datasetIdx);

% --- Base directory selection ---
useLocalBaseDir           = false;  % <-- set true to use script location, false to use manual path

if useLocalBaseDir
    % Use folder where this script is located
    thisScriptPath        = mfilename('fullpath');
    [thisScriptDir, ~, ~] = fileparts(thisScriptPath);
    baseDir               = fullfile(thisScriptDir, 'Results');
else
    % Use manually specified folder
    baseDir               = 'E:\Results - Experiment\202508\BECToStripes\';
end

% --- Build paths ---
dataFile                  = fullfile(baseDir, 'SavedData', [datasetName '.mat']);
figSaveDir                = fullfile(baseDir, 'SavedFigures', datasetName);

% --- Load dataset ---
data                      = load(dataFile);

% --- Ensure figure folder exists ---
if ~exist(figSaveDir, 'dir')
    mkdir(figSaveDir);
end

% --- Access dataset struct dynamically ---
datasetStruct             = data.(datasetName);
compiled_results          = datasetStruct.results;
scan_parameter_values     = datasetStruct.scan_parameter_values;
scan_reference_values     = datasetStruct.scan_reference_values;

% --- Load options used during analysis ---
options                   = datasetStruct.options;
options.font              = 'Bahnschrift';   % override if needed
options.skipSaveFigures   = false;           % override if needed


%% ------------------ 1. Mean ± Std Plots ------------------
% Plot Radial Spectral Contrast
Plotter.plotMeanWithSE(scan_parameter_values, compiled_results.spectral_analysis_results.radial_spectral_contrast, ...
    'Title', options.titleString, ...
    'XLabel', 'B (G)', ...
    'YLabel', 'Radial Spectral Contrast', ...
    'FigNum', 1, ...
    'FontName', options.font, ...
    'SaveFileName', 'RadialSpectralContrast.fig', ...
    'SaveDirectory', figSaveDir, ...   % save figures inside dataset-specific folder
    'SkipSaveFigures', options.skipSaveFigures);

% Plot Angular Spectral Weight
Plotter.plotMeanWithSE(scan_parameter_values, compiled_results.spectral_analysis_results.angular_spectral_weight, ...
    'Title', options.titleString, ...
    'XLabel', 'B (G)', ...
    'YLabel', 'Angular Spectral Weight', ...
    'FigNum', 2, ...
    'FontName', options.font, ...
    'SaveFileName', 'AngularSpectralWeight.fig', ...
    'SaveDirectory', figSaveDir, ...
    'SkipSaveFigures', options.skipSaveFigures);

% Plot Peak Offset Angular Correlation
Plotter.plotMeanWithSE(scan_parameter_values, compiled_results.custom_g_results.max_g2_all_per_scan_parameter_value, ...
    'Title', options.titleString, ...
    'XLabel', 'B (G)', ...
    'YLabel', '$\mathrm{max}[g^{(2)}_{[50,70]}(\delta\theta)]$', ...
    'FigNum', 3, ...
    'YLim', [0 1], ...
    'FontName', options.font, ...
    'SaveFileName', 'PeakOffsetAngularCorrelation.fig', ...
    'SaveDirectory', figSaveDir, ...
    'SkipSaveFigures', options.skipSaveFigures);

%% ------------------ 2. PDF of Radial Spectral Contrast across transition ------------------

% Ensure row vectors
contrast  = compiled_results.spectral_analysis_results.radial_spectral_contrast(:)';
params    = scan_parameter_values(:)';
reference = scan_reference_values(:)';

% Preallocate a cell array to hold grouped results
grouped_contrast = cell(size(reference));  % 1x21

% Loop over each unique reference value
for i = 1:length(reference)
    ref_val = reference(i);
    
    % Find indices where the scan param matches this reference
    idx = params == ref_val;
    
    % Store corresponding contrast values
    grouped_contrast{i} = contrast(idx);
end

Plotter.plotPDF(grouped_contrast, ...
    scan_reference_values, ...
    'Title', options.titleString, ...
    'XLabel', 'B (G)', ...
    'YLabel', 'Radial Spectral Contrast', ...
    'FigNum', 4, ...
    'FontName', options.font, ...
    'SkipSaveFigures', options.skipSaveFigures, ...
    'SaveFileName', 'PDF_MaxG2AcrossTransition.fig', ...
    'SaveDirectory', figSaveDir, ...
    'NumberOfBins', 20, ... 
    'NormalizeHistogram', true, ... 
    'DataRange', [0 0.1], ...
    'Colormap', @Colormaps.coolwarm, ...
    'XLim', [min(scan_reference_values) max(scan_reference_values)]);

%% ------------------ 3. Cumulants across transition ------------------

maxOrder        = 4;  % Set the order of cumulants you want
numGroups       = length(grouped_contrast);

% Preallocate matrix to store cumulants
% Each row corresponds to a group (i.e., a scan_reference_value)
% Each column corresponds to a cumulant order (1 to maxOrder)
cumulant_matrix = NaN(numGroups, maxOrder);

for i = 1:numGroups
    data_i = grouped_contrast{i};
    cumulant_matrix(i, :) = Calculator.computeCumulants(data_i, maxOrder);
end

mean_rsc   = cumulant_matrix(:, 1);
var_rsc    = cumulant_matrix(:, 2);
skew_rsc   = cumulant_matrix(:, 3);
binder_rsc = cumulant_matrix(:, 4);

Plotter.plotCumulants(scan_reference_values, ...
    {mean_rsc, var_rsc, skew_rsc, binder_rsc}, ...
    'Title', 'Cumulants of Radial Spectral Contrast', ...
    'XLabel', 'B (G)', ...
    'FigNum', 5, ...
    'FontName', options.font, ...
    'MarkerSize', 6, ...
    'LineWidth', 1.5, ...
    'SkipSaveFigures', options.skipSaveFigures, ...
    'SaveFileName', 'CumulantOfPeakOffsetAngularCorrelation.fig', ...
    'SaveDirectory', figSaveDir);

%% ------------------ 4. Features of g²(θ) across transition ------------------

g2_analysis_results = Analyzer.analyzeAutocorrelation(compiled_results.full_g2_results);

Plotter.plotG2Curves(compiled_results.full_g2_results, ...
    'Title', options.titleString, ...
    'XLabel', '\delta\theta / \pi', ...
    'YLabel', 'g^{(2)}(\delta\theta)', ...
    'HighlightEvery', 10, ...              % highlight every 10th repetition
    'FontName', options.font, ...
    'FigNum', 6, ...
    'TileTitlePrefix', '\alpha', ...       % user-defined tile prefix
    'TileTitleSuffix', '^\circ', ...       % user-defined suffix (e.g., Gauss symbol)...
    'SkipSaveFigures', options.skipSaveFigures, ...
    'SaveFileName', 'G2Curves.fig', ...
    'SaveDirectory', figSaveDir);

Plotter.plotG2PDF(compiled_results.full_g2_results, pi/2, ...
    'Title', options.titleString, ...
    'XLabel', '\alpha', ...
    'YLabel', 'g^{(2)}(\delta\theta)', ...
    'FontName', options.font, ...
    'FontSize', 16, ...
    'FigNum', 7, ...
    'SkipSaveFigures', options.skipSaveFigures, ...
    'SaveFileName', 'G2PDF_pi6.fig', ...
    'SaveDirectory', figSaveDir, ...
    'NumberOfBins', 20, ... 
    'NormalizeHistogram', true, ... 
    'DataRange', [0 1.0], ...
    'Colormap', @Colormaps.coolwarm, ...
    'ColorScale', 'log', ...
    'XLim', [min(scan_reference_values) max(scan_reference_values)]);

Plotter.plotG2Features(g2_analysis_results, ...
    'Title', options.titleString, ...
    'XLabel', '\alpha (degrees)', ...
    'FontName', options.font, ...
    'FigNum', 8, ...
    'SkipSaveFigures', options.skipSaveFigures, ...
    'SaveFileName', 'G2Features.fig', ...
    'SaveDirectory', figSaveDir);

Plotter.plotG2Cumulants(g2_analysis_results, ...
    'Title', options.titleString, ...
    'XLabel', '\alpha (degrees)', ...
    'FontName', options.font, ...
    'FigNum', 9, ...
    'SkipSaveFigures', options.skipSaveFigures, ...
    'SaveFileName', 'G2Cumulants.fig', ...
    'SaveDirectory', figSaveDir);

%% ------------------ 5. PDF of max g² across transition ------------------
Plotter.plotPDF(compiled_results.custom_g_results.max_g2_all_per_scan_parameter_value, ...
    scan_reference_values, ...
    'Title', options.titleString, ...
    'XLabel', 'B (G)', ...
    'YLabel', '$\mathrm{max}[g^{(2)}_{[50,70]}(\delta\theta)]$', ...
    'FigNum', 10, ...
    'FontName', options.font, ...
    'SkipSaveFigures', options.skipSaveFigures, ...
    'SaveFileName', 'PDF_MaxG2AcrossTransition.fig', ...
    'SaveDirectory', figSaveDir, ...
    'NumberOfBins', 20, ... 
    'NormalizeHistogram', true, ... 
    'DataRange', [0 1.5], ...
    'Colormap', @Colormaps.coolwarm, ...
    'XLim', [min(scan_reference_values) max(scan_reference_values)]);


%% ------------------ 5. Cumulants across transition ------------------
Plotter.plotCumulants(scan_reference_values, ...
    {compiled_results.custom_g_results.mean_max_g2, compiled_results.custom_g_results.var_max_g2, compiled_results.custom_g_results.skew_max_g2_angle, compiled_results.custom_g_results.fourth_order_cumulant_max_g2}, ...
    'Title', 'Cumulants of Peak Offset Angular Correlation', ...
    'XLabel', 'B (G)', ...
    'FigNum', 11, ...
    'FontName', options.font, ...
    'SkipSaveFigures', options.skipSaveFigures, ...
    'SaveFileName', 'CumulantOfPeakOffsetAngularCorrelation.fig', ...
    'SaveDirectory', figSaveDir);

%% ------------------ 6. PCA ------------------
Plotter.plotSinglePCAResults(compiled_results.pca_results, scan_parameter_values, scan_reference_values, ...
    'FigNumRange', [12,13,14,15,16,17], ...
    'XLabel', 'B (G)', ...
    'FontName', options.font, ...
    'SkipSaveFigures', options.skipSaveFigures, ...
    'SaveDirectory', figSaveDir);


Plotter.plotMultiplePCAResults(compiled_results.pca_results, scan_parameter_values, scan_reference_values, ...
    'MaxPCToPlot', 2, ...
    'XLabel', 'B (G)', ...
    'FigNumRange', [18,19,20], ...
    'FontName', options.font, ...
    'SkipSaveFigures', options.skipSaveFigures, ...
    'SaveDirectory', figSaveDir);

%{
%% ------------------ 7. Average of Spectra Plots ------------------

Plotter.plotAverageSpectra(scan_parameter_values, ...
     spectral_analysis_results, ...
     'ScanParameterName', scan_parameter, ...
     'FigNum', 21, ...
     'ColormapPS', Colormaps.coolwarm(), ...
     'Font', 'Bahnschrift', ...
     'SaveFileName', 'avgSpectra.fig', ...
     'SaveDirectory', figSaveDir, ...
     'SkipSaveFigures', options.skipSaveFigures);
%}