clc; clear; close all;

%% ===================== LOAD TABLES =====================
load('TAB_tol_hoop.mat');         T_hoop   = TAB_tol_hoop;
load('TAB_tol_spiral.mat');  T_spiral = TAB_tol_spiral;
load('TAB_tol_tweel.mat');   T_tweel  = TAB_tol_tweel;
load('TAB_tol_twin.mat');        T_twin   = TAB_tol_twin;

arch = {'Hoop','Spiral','Tweel','Twin'};
tables = {T_hoop, T_spiral, T_tweel, T_twin};

%% ===================== COLUMN NAMES =====================
col_t_ext  = 't ext [m]';
col_t_int  = 't int [m]';
col_t_rinf = 't rinf [m]';
col_mass   = 'Wheel mass [kg]';

t0  = 0.003;     % baseline thickness [m]
tol = 1e-12;     % tolerance for float comparison (increase if needed)

%% ===================== FILTER BASELINE + COMPUTE MASS =====================
m_mean = nan(1,4);
m_med  = nan(1,4);
n_rows = zeros(1,4);

for i = 1:4
    T = tables{i};

    % Check columns exist
    assert(ismember(col_t_ext,  T.Properties.VariableNames), 'Missing column: %s', col_t_ext);
    assert(ismember(col_t_int,  T.Properties.VariableNames), 'Missing column: %s', col_t_int);
    assert(ismember(col_t_rinf, T.Properties.VariableNames), 'Missing column: %s', col_t_rinf);
    assert(ismember(col_mass,   T.Properties.VariableNames), 'Missing column: %s', col_mass);

    % Filter baseline rows
    idx = abs(T.(col_t_ext)  - t0) < tol & ...
          abs(T.(col_t_int)  - t0) < tol & ...
          abs(T.(col_t_rinf) - t0) < tol;

    Tb = T(idx, :);
    n_rows(i) = height(Tb);

    if n_rows(i) == 0
        warning('%s: no rows found with t_ext=t_int=t_rinf=0.003.', arch{i});
        continue;
    end

    m_mean(i) = mean(Tb.(col_mass), 'omitnan');
    m_med(i)  = median(Tb.(col_mass), 'omitnan');
end

%% ===================== MASS-ONLY COST INDEX =====================
% Usa mean (o cambia in mediana se preferisci)
m = m_mean;

% Normalized cost index (higher mass -> higher cost)
Cstar = m / max(m);

% Score 1-5: lowest mass = 5, highest mass = 1
[~, rank] = sort(Cstar, 'ascend');
score = zeros(size(Cstar));
score(rank) = [5 4 3 2];

T_cost = table(arch', n_rows', m_mean', m_med', Cstar', score', ...
    'VariableNames', {'Architecture','N_baseline_rows','MeanMass_kg','MedianMass_kg', ...
                      'CostIndex_massOnly','EstimatedCostScore_1to5'});

disp(T_cost)

%% ===================== OPTIONAL PLOT =====================
figure('Color','w');
bar(Cstar)
set(gca,'XTickLabel',arch,'FontSize',20)
ylabel('Mass-based cost index (normalized)', Interpreter='latex',FontSize=30)
% title('Estimated cost (mass-only) using baseline thickness t=0.003 m')
grid on

ax = gca;
ax.FontSize = 14;
ax.LineWidth = 1;
ax.TickLabelInterpreter = 'latex';
