% Clear the Command Window
clc;

% Clear the workspace
clear;

% Close all figures
close all;

% Define the list of file paths and their corresponding legends
filePaths = {
    'C:\Users\anupa\Desktop\My files\PhD\experiments\@TUHH\meas\Circular electrode V1 capacitive\1to1M\sweep_00000.mat', 'Circular electrode V1 capacitive';
    'C:\Users\anupa\Desktop\My files\PhD\experiments\@TUHH\meas\Circular electrode V1 conductive\1to1M\sweep_00000.mat', 'Circular electrode V1 conductive';
    'C:\Users\anupa\Desktop\My files\PhD\experiments\@TUHH\meas\Circular electrode V2 capacitive\1to1M\sweep_00000.mat', 'Circular electrode V2 capacitive';
    'C:\Users\anupa\Desktop\My files\PhD\experiments\@TUHH\meas\Circular electrode V2 conductive\1to1M\sweep_00000.mat', 'Circular electrode V2 conductive';
    % Add more file paths and legends as needed
};

% Initialize cell arrays to store legends
magnitudeLegends = {};
phaseLegends = {};

% Initialize variables to store global min and max values
globalFreqMin = Inf;
globalFreqMax = -Inf;
globalMagMin = Inf;
globalMagMax = -Inf;
globalPhaseMin = Inf;
globalPhaseMax = -Inf;

% Data storage for plotting
allFrequency = {};
allMagnitude = {};
allPhase = {};

% Loop through each file to determine the global min and max values
for i = 1:size(filePaths, 1)
    try
        % Load the .mat file
        data = load(filePaths{i, 1});
        
        % Access the contents of the 'dev7429' field
        subData = data.dev7429;
        
        % Access the contents of the 'imps' field
        impsData = subData.imps;
        
        % Access the contents of the 'sample' field
        sampleData = impsData.sample;
        
        % If sampleData is a cell, access its content
        if iscell(sampleData)
            % Assuming the cell contains one structure, extract it
            sampleData = sampleData{1};
        end
        
        % Check if sampleData is a structure and list its fields
        if isstruct(sampleData)
            % Assuming the 'sample' structure contains 'frequency', 'absz', and 'phasez' fields
            if isfield(sampleData, 'frequency') && isfield(sampleData, 'absz') && isfield(sampleData, 'phasez')
                % Access specific variables
                frequency = sampleData.frequency;
                magnitude = sampleData.absz;
                phase = sampleData.phasez;
                
                % Convert frequency, magnitude, and phase to column vectors if they are not already
                frequency = frequency(:);
                magnitude = magnitude(:);
                phase = phase(:);
                
                % Check if the phase is in radians and convert to degrees if necessary
                if max(abs(phase)) <= 2*pi
                    phase = rad2deg(phase); % Convert radians to degrees
                end
                
                % Update global min and max values
                globalFreqMin = min(globalFreqMin, min(frequency));
                globalFreqMax = max(globalFreqMax, max(frequency));
                globalMagMin = min(globalMagMin, min(magnitude));
                globalMagMax = max(globalMagMax, max(magnitude));
                globalPhaseMin = min(globalPhaseMin, min(phase));
                globalPhaseMax = max(globalPhaseMax, max(phase));
                
                % Store data for plotting
                allFrequency{end+1} = frequency;
                allMagnitude{end+1} = magnitude;
                allPhase{end+1} = phase;
                
                % Add legends
                magnitudeLegends{end+1} = filePaths{i, 2}; % Use the custom legend
                phaseLegends{end+1} = filePaths{i, 2};     % Use the custom legend
            else
                disp(['The variables "frequency", "absz", and "phasez" were not found in the sample structure for file: ', filePaths{i, 1}]);
            end
        else
            disp(['The variable "sample" is not a structure and cannot be processed for file: ', filePaths{i, 1}]);
        end
    catch ME
        disp(['Error processing file: ', filePaths{i, 1}]);
        disp(['Error message: ', ME.message]);
    end
end

% Create a single figure for both magnitude and phase
figure;
hold on;

% Create subplots
magnitudeAx = subplot(2, 1, 1); % Magnitude plot will be the first subplot
hold on;
phaseAx = subplot(2, 1, 2); % Phase plot will be the second subplot
hold on;

% Plot all data with consistent scaling
for i = 1:length(allFrequency)
    % Plot the magnitude
    axes(magnitudeAx); % Set current axes to magnitude subplot
    loglog(allFrequency{i}, allMagnitude{i}); % Magnitude in log scale
    xlabel('Frequency (Hz)');
    ylabel('Magnitude (Ohms)');
    title('Bode Plot - Magnitude');
    grid on;
    xlim([globalFreqMin globalFreqMax]);
    ylim([globalMagMin globalMagMax]);
    
    % Plot the phase
    axes(phaseAx); % Set current axes to phase subplot
    semilogx(allFrequency{i}, allPhase{i}); % Phase in degrees
    xlabel('Frequency (Hz)');
    ylabel('Phase (degrees)');
    title('Bode Plot - Phase');
    grid on;
    xlim([globalFreqMin globalFreqMax]);
    ylim([globalPhaseMin globalPhaseMax]);
end

% Set the scaling and legends for the subplots
axes(magnitudeAx);
set(gca, 'XScale', 'log', 'YScale', 'log');
legend(magnitudeLegends);

axes(phaseAx);
set(gca, 'XScale', 'log');
legend(phaseLegends);
