%% MASTER SCRIPT: BODE PLOTS FOR DRYING COATING (SORTED LEGEND)
clear; clc; close all;

% =========================================================================
% 1. USER CONFIGURATION
% =========================================================================
baseDir = 'C:\Users\anupa\Desktop\My files\PhD\experiments\pre_meas_data_2025\coating_exp_w_drying';

% =========================================================================
% 2. DEFINE DATA 
% =========================================================================
% --- SERIES 1 ---
s1_names = {'C_Co_V1_t00'; 'C_Co_V1_t01'; 'C_Co_V1_t02'; 'C_Co_V1_t03'; 'C_Co_V1_t04'; 'C_Co_V1_t05'};
s1_moist = [0; 70; 59.78807947; 30.68493151; 6.871165644; 5.125];

% --- SERIES 2 --- 
s2_names = {'C_Co_V1_t00'; 'C_Co_V1_t01'; 'C_Co_V1_t02'; 'C_Co_V1_t03'; 'C_Co_V1_t04'; 'C_Co_V1_t05'; 'C_Co_V1_t07'};
s2_moist = [0; 70; 66.2300885; 57.78761062; 40.09419152; 17.46214852; 9.858267717];

folderNames = {'Series_1', 'Series_2'};
allSeriesNames = {s1_names, s2_names};
allSeriesMoist = {s1_moist, s2_moist};

% =========================================================================
% 3. PROCESSING & PLOTTING
% =========================================================================
for s = 1:2
    names = allSeriesNames{s};
    moist = allSeriesMoist{s};
    folderPath = fullfile(baseDir, folderNames{s});
    
    figure('Name', sprintf('Bode Plot - Series %d', s), 'Color', 'w', 'Position', [100+(s*50), 100+(s*50), 800, 700]);
    colors = lines(length(names)); 
    
    % Preallocate an array to hold the plot handles for the legend
    h_lines = gobjects(length(names), 1);
    
    for i = 1:length(names)
        fname = sprintf('%s.txt', names{i});
        fullFile = fullfile(folderPath, fname);
        
        if isfile(fullFile)
            [f_m, mag, f_p, phase] = extractBodeData(fullFile);
            
            % Format the line styles and legend string
            if moist(i) == 0
                legStr = 'No coating';
                c_line = [0.6 0.6 0.6]; % Grey
                s_line = ':'; % Dash-dot
                w_line = 3.5; % Extra thick
            else
                legStr = sprintf('%.1f%%', moist(i));
                c_line = colors(i,:); 
                s_line = '-';
                w_line = 2;
                
                % Override the color for 17.5% to dark blue
                if abs(moist(i) - 17.462) < 0.1
                    c_line = [0 0 0.6]; 
                end
                
                % Override the color for 9.9% to light blue
                if abs(moist(i) - 9.858) < 0.1
                    c_line = [0.4 0.8 1.0]; 
                end
            end
            
            % Plot Magnitude (Top Subplot)
            subplot(2, 1, 1);
            hold on;
            if ~isempty(f_m)
                h_lines(i) = plot(f_m, mag, 'LineStyle', s_line, 'LineWidth', w_line, 'Color', c_line, ...
                    'DisplayName', legStr);
            end
            
            % Plot Phase (Bottom Subplot)
            subplot(2, 1, 2);
            hold on;
            if ~isempty(f_p)
                plot(f_p, phase, 'LineStyle', s_line, 'LineWidth', w_line, 'Color', c_line, 'HandleVisibility', 'off');
            end
        else
            fprintf('Missing: %s\n', fullFile);
        end
    end
    
    % Sort the legend by moisture (ascending)
    valid_idx = isgraphics(h_lines); % Only grab lines that actually plotted
    valid_handles = h_lines(valid_idx);
    valid_moist = moist(valid_idx);
    
    [~, sort_order] = sort(valid_moist);
    
    % Format Magnitude Subplot
subplot(2, 1, 1);
set(gca, 'XScale', 'log', 'YScale', 'log', 'FontSize', 16);
grid on;
ylabel('Impedance (\Omega)', 'FontSize', 16);
legend(valid_handles(sort_order), 'Location', 'best', 'NumColumns', 2, 'FontSize', 16);

% Format Phase Subplot
subplot(2, 1, 2);
set(gca, 'XScale', 'log', 'FontSize', 16);
grid on;
xlabel('Frequency (Hz)', 'FontSize', 16);
ylabel('Phase (\circ)', 'FontSize', 16);
ylim([-100 10]);
    
    hold off;
end

disp('Plotting complete.');

% =========================================================================
% 4. HELPER FUNCTION: SLICE STACKED ARRAYS
% =========================================================================
function [f_m, mag, f_p, phase] = extractBodeData(filepath)
    f_m = []; mag = []; f_p = []; phase = [];
    try
        opts = detectImportOptions(filepath);
        opts.CommentStyle = '%';
        opts.Delimiter = ';';
        opts.DataLines = [1 Inf];
        opts.VariableNamingRule = 'preserve';
        
        raw = readmatrix(filepath, opts);
        if isempty(raw), return; end
        
        freq = raw(:,1); 
        val = raw(:,2);
        
        % Slice the array precisely in half
        split_idx = floor(length(freq) / 2);
        
        f_m = freq(1:split_idx);
        mag = val(1:split_idx);
        
        f_p = freq(split_idx+1:end);
        phase = val(split_idx+1:end);
        
        % Sort frequencies ascending to prevent lines drawing backwards
        [f_m, idx_m] = sort(f_m);
        mag = mag(idx_m);
        
        [f_p, idx_p] = sort(f_p);
        phase = phase(idx_p);
    catch
    end
end