clearvars;
close all;

num_tests = 5;
num_decoders = [1, 2, 3, 4, 5, 6, 7, 8];
L_max = [2, 3, 4, 5, 6, 7, 8];
MSE_ours = zeros(num_tests, length(num_decoders), length(L_max));
MSE_baseline = zeros(num_tests, length(num_decoders), length(L_max));
Beta_ours = zeros(num_tests, length(num_decoders), length(L_max));
Beta_baseline = zeros(num_tests, length(num_decoders), length(L_max));
N_ours = zeros(num_tests, length(num_decoders), length(L_max));
N_baseline = zeros(num_tests, length(num_decoders), length(L_max));

for n = 1:num_tests
    S = readlines(sprintf('out_%02d.txt', n));
    [M1, M2, B1, B2, N1, N2] = get_matrices(S, num_decoders, L_max);
    MSE_ours(n, :, :) = M1;
    MSE_baseline(n, :, :) = M2;
    Beta_ours(n, :, :) = B1;
    Beta_baseline(n, :, :) = B2;
    N_ours(n, :, :) = N1;
    N_baseline(n, :, :) = N2;
end

MSE_ours_std = squeeze(std(MSE_ours, 0, 1)) / sqrt(num_tests);
MSE_ours = squeeze(mean(MSE_ours, 1));
MSE_baseline_std = squeeze(std(MSE_baseline, 0, 1)) / sqrt(num_tests);
MSE_baseline = squeeze(mean(MSE_baseline, 1));
Beta_ours = squeeze(mode(Beta_ours, 1));
Beta_baseline = squeeze(mode(Beta_baseline, 1));
N_ours = squeeze(mode(N_ours, 1));
N_baseline = squeeze(mode(N_baseline, 1));

function [M_ours, M_baseline, Beta_ours, Beta_baseline, N_ours, N_baseline] = get_matrices(S, num_decoders, L_max)
    sz1 = length(num_decoders);
    sz2 = length(L_max);

    M_ours = zeros(sz1, sz2);
    M_baseline = zeros(sz1, sz2);
    Beta_ours = zeros(sz1, sz2);
    Beta_baseline = zeros(sz1, sz2);
    N_ours = zeros(sz1, sz2);
    N_baseline = zeros(sz1, sz2);
    type = '';

    for i = 1:length(S)
        str = S(i);
        if startsWith(str, 'Testing normal scheme')
            type = 'normal';
        elseif startsWith(str, 'Testing baseline scheme')
            type = 'baseline';
        elseif endsWith(str, '(BEST)')
            A = sscanf(str, 'K=%d  log(Lmax)=%d  log(N)=%d  beta=%f  DecoderMSE=%f  EncoderMSE=%f', 6);
            K = A(1);
            L = A(2);
            N = A(3);
            Beta = A(4);
            DecoderMSE = A(5);

            K_idx = find(num_decoders == K);
            L_idx = find(L_max == L);

            if strcmp(type, 'normal')
                M_ours(K_idx, L_idx) = DecoderMSE;
                Beta_ours(K_idx, L_idx) = Beta;
                N_ours(K_idx, L_idx) = N;
            elseif strcmp(type, 'baseline')
                M_baseline(K_idx, L_idx) = DecoderMSE;
                Beta_baseline(K_idx, L_idx) = Beta;
                N_baseline(K_idx, L_idx) = N;
            end
        end
    end
end