% Clear the workspace
clear;

% Close all figures
close all;

% Full paths to the .mat files
filePaths = {'C:\Users\anupa\Documents\MATLAB\measurements\cap1.mat', ...
             'C:\Users\anupa\Documents\MATLAB\measurements\con2.mat'};

% Humidity values for each dataset
humidityValues = {
    [51.11, 26.82, 18.91, 11.35, 5.47, 0.0], ...
    [76.14, 56.22, 41.90, 34.64, 20.43, 5.18, 3.18, 1.00, 0.00]
};

% Legend names for each file
legendNames = {
    {'Cap1 26.82%', 'Cap1 0.0%'}, ...
    {'Con2 76.14%', 'Con2 34.64%'}
};

% Indices of the required humidity values
indices = {
    [2, 6], ... % Indices for Cap1 (26.82% and 0.0%)
    [1, 4]  ... % Indices for Con2 (76.14% and 34.64%)
};

% Create a figure with two subplots
figure;

% Initialize arrays to store legend entries and capacitance values
combinedLegendNamesMag = {};
combinedLegendNamesPhase = {};
capacitanceValues = {};

% Loop through each file to plot the data separately
for f = 1:length(filePaths)
    % Load the .mat file
    data = load(filePaths{f});

    % List all fields in the data structure
    fields = fieldnames(data);

    % Loop through the required indices to plot the data separately
    for i = indices{f}
        fieldName = fields{i};
        fieldData = data.(fieldName);

        % Extract magnitude, frequency, and phase from the field data
        mag = fieldData(1, :);
        freq = fieldData(2, :);
        phase = fieldData(3, :) * (180 / pi); % Convert phase to degrees

        % Extract capacitance values at specified frequencies
        specified_freqs = [1000, 10000, 100000]; % Example frequencies in Hz
        capacitance_at_freqs = zeros(size(specified_freqs));
        for k = 1:length(specified_freqs)
            [~, idx] = min(abs(freq - specified_freqs(k)));
            capacitance_at_freqs(k) = 1 / (2 * pi * freq(idx) * mag(idx));
        end
        capacitanceValues{end+1} = struct('Humidity', legendNames{f}{find(indices{f} == i)}, 'Frequencies', specified_freqs, 'Capacitance', capacitance_at_freqs);

        % Prepare legend entry without capacitance values
        legendEntry = legendNames{f}{find(indices{f} == i)};

        % Plot each dataset separately in respective subplots
        % Plot magnitude data
        subplot(2, 1, 1);
        loglog(freq, mag, 'DisplayName', legendEntry);
        hold on;

        % Plot phase data
        subplot(2, 1, 2);
        semilogx(freq, phase, 'DisplayName', legendEntry);
        hold on;

        % Append the legend entry
        combinedLegendNamesMag{end+1} = legendEntry;
        combinedLegendNamesPhase{end+1} = legendEntry;
    end
end

% Combined Magnitude subplot
subplot(2, 1, 1);
xlabel('Frequency (Hz)');
ylabel('Impedance Magnitude (\Omega)');
title('Magnitude vs Frequency - Selected Data Points');
set(gca, 'XScale', 'log', 'YScale', 'log');
grid on;
legend(combinedLegendNamesMag, 'Location', 'best');

% Combined Phase subplot
subplot(2, 1, 2);
xlabel('Frequency (Hz)');
ylabel('Phase (degrees)');
title('Phase vs Frequency - Selected Data Points');
set(gca, 'XScale', 'log');
grid on;
legend(combinedLegendNamesPhase, 'Location', 'best');

% Prepare capacitance values text for annotation
cap_text = sprintf('Humidity\t\tFrequencies (Hz)\t\t\t\tCapacitance (F)\n');
for i = 1:length(capacitanceValues)
    freq_str = sprintf('%d\t', capacitanceValues{i}.Frequencies);
    cap_str = sprintf('%.3e\t', capacitanceValues{i}.Capacitance);
    cap_text = [cap_text, sprintf('%s\t%s\t%s\n', capacitanceValues{i}.Humidity, freq_str, cap_str)];
end

% Add capacitance values annotation outside the plot on the right side
annotation('textbox', [0.8, 0.1, 0.19, 0.8], 'String', cap_text, 'FitBoxToText', 'on', 'BackgroundColor', 'white', 'Interpreter', 'none');

% Adjust figure size to accommodate the textbox
set(gcf, 'Position', [100, 100, 1200, 600]);

% Display capacitance values in command window for reference
for i = 1:length(capacitanceValues)
    disp(['Humidity: ', capacitanceValues{i}.Humidity]);
    disp(['Frequencies (Hz): ', num2str(capacitanceValues{i}.Frequencies)]);
    disp(['Capacitance (F): ', num2str(capacitanceValues{i}.Capacitance)]);
    disp('---');
end
