data = load("5_2_2025_movements_M1.mat")
data_M2 = load("5_2_2025_movements_M2.mat");
emg_M2 = data_M2.data;

emg = data.data;
emgBipol(:,1) = emg(:,2) - emg(:,1);
emgBipol(:,2) = emg(:,5) - emg(:,4);
emgBipol(:,3) = emg(:,5) - emg(:,3);
emgBipol(:,4) = emg(:,6) - emg(:,5);
emgBipol(:,5) = emg(:,7) - emg(:,5);
emgBipol(:,6) = emg(:,9) - emg(:,8);
emgBipol(:,7) = emg(:,11) - emg(:,10);
emgBipol(:,8) = emg(:,13) - emg(:,12);
label = {'PP3', 'PP2A', 'PP2B', 'PP1A', 'PP1B', 'PL2', 'ZP3', 'ZP2'}; 


emgBipol_M2(:,1) = emg_M2(:,2) - emg_M2(:,1);
emgBipol_M2(:,2) = emg_M2(:,5) - emg_M2(:,4);
emgBipol_M2(:,3) = emg_M2(:,5) - emg_M2(:,3);
emgBipol_M2(:,4) = emg_M2(:,6) - emg_M2(:,5);
emgBipol_M2(:,5) = emg_M2(:,7) - emg_M2(:,5);
emgBipol_M2(:,6) = emg_M2(:,9) - emg_M2(:,8);
emgBipol_M2(:,7) = emg_M2(:,11) - emg_M2(:,10);
emgBipol_M2(:,8) = emg_M2(:,13) - emg_M2(:,12);
emgBipol_M2(:,9) = emg_M2(:,14) - emg_M2(:,13);  


%


bloky = [
    14104, 19112;
    19314, 27339;
    36613, 49288;
    60020, 67641;
    73185, 81489;
    84993, 97682;
    101583, 111301
];

max_zatizeni = zeros(8, 1); 
fs = 1000;
[b_high, a_high] = butter(4, 20 / (fs / 2), 'high');

[b_low, a_low] = butter(4, 450 / (fs / 2), 'low');

[b_smooth, a_smooth] = butter(4, 5 / (fs / 2), 'low');

for i = 1:8 
    maxima = [];
    for b = 1:size(bloky, 1)
        segment = emgBipol_M2(bloky(b,1):bloky(b,2), i);
        sig_hp = filtfilt(b_high, a_high, segment);
        sig_lp = filtfilt(b_low, a_low, sig_hp);
        envelope = abs(hilbert(sig_lp));
        envelope_smooth = filtfilt(b_smooth, a_smooth, envelope);
        maxima(end+1) = max(envelope_smooth);
    end
    max_zatizeni(i) = max(maxima);
end

%


% start_of_1 = 734083;
start_of_1 = 734083 - 1862;
% end_of_1 = 867657
end_of_1 = 867657 + 2000;
cvik_1 = emgBipol(start_of_1:end_of_1, :);


figure;
for i = 1:8
    subplot(8,1,i);
    plot(cvik_1(:,i));
    ylabel(label{i});
    if i == 1
        title('EMG signál - M1 - first');
    end
end
xlabel('Časové vzorky');
grid on;

%


% Parametry filtrů
fs = 1000;
fc_low = 150;  % Mezní frekvence dolní propusti (low-pass)
fc_high = 50;  % Mezní frekvence horní propusti (high-pass)
order = 4;     % Řád filtru

[b_high, a_high] = butter(order, fc_high/(fs/2), 'high');

[b_low, a_low] = butter(order, fc_low/(fs/2), 'low');

cvik_filtered = filtfilt(b_high, a_high, cvik_1);


cvik_filtered = filtfilt(b_low, a_low, cvik_filtered);

figure;
for i = 1:8
    subplot(8,1,i);
    plot(cvik_filtered(:,i));
    ylabel(label{i});
    if i == 1
        title('Filtrovaný EMG signál - M1 - first');
    end
end
xlabel('Časové vzorky');
grid on;


% Výpočet obálky pomocí Hilbertovy transformace
envelopes = abs(hilbert(cvik_filtered))';  


fc_smooth = 3;  % Mezní frekvence dolní propusti (5 Hz)
order = 4;      % Řád filtru


[b_smooth, a_smooth] = butter(order, fc_smooth/(fs/2), 'low');


envelopes_smooth = filtfilt(b_smooth, a_smooth, envelopes')';  
figure;
for i = 1:size(envelopes_smooth, 1)
    subplot(size(envelopes_smooth, 1), 1, i);
    plot(envelopes_smooth(i, :), 'b', 'LineWidth', 1.5); % Vyhlazená obálka
    ylabel([label(i)]);
    if i == 1
        title('Vyhlazené obálky Bipol komponent - M1 -first');
    end
end
xlabel('Časové vzorky');
grid on;

%

reference_index = 2;
numElectrodes = size(envelopes_smooth, 1);

intervals = [
     0,     9300;
  9405,   18705;
 17943,   27243;
 25634,   34934;
 34738,   44038;
 44475,   53775;
 53931,   63231;
 62329,   71629;
 71078,   80378;
 80534,   89834;
 89849,   99149;
 99162,  108462;
108477, 117777;
117369, 126669;
126472, 135772
];
numElectrodes = size(envelopes_smooth, 1);  % mělo by být 8
numSegments = size(intervals, 1);
segmentLength = intervals(1, 2) - intervals(1, 1);


time_axis = (0:segmentLength - 1) / fs;  % čas v sekundách

% Uložení výsledků
all_segments = cell(numElectrodes, 1);
mean_segments = cell(numElectrodes, 1);
idx_P5 = find(strcmp(label, 'PP3'));
idx_P6 = find(strcmp(label, 'ZP3'));


for i = 1:numElectrodes
    if i == idx_P5 || i == idx_P6
         continue; 
    end

    sig = envelopes_smooth(i, :);
    segments = zeros(numSegments, segmentLength);

    for j = 1:numSegments
        t0 = intervals(j, 1);
        t1 = intervals(j, 2);
        segments(j, :) = sig(t0+1:t1);  % výřez signálu
    end

    mean_seg = mean(segments, 1);

    % Uložení
    all_segments{i} = segments;
    mean_segments{i} = mean_seg

    figure;
    hold on;
    
    for j = 1:numSegments
        h_segments(j) = plot(time_axis, segments(j, :), 'Color', [0.4, 0.4, 1]);
    end
    
    h_mean = plot(time_axis, mean_seg, 'r', 'LineWidth', 2);
    
    title(['Segmenty a průměr - ' label{i}]);
    xlabel('Čas [s]');
    ylabel('Amplituda');
    
    legend([h_segments(1), h_mean], {'Jednotlivé segmenty', 'Průměrná obálka'});
    
    grid on;

end

upper_threshold_factor = 0.46;  % Horní práh jako 46 % maxima
lower_threshold_factor = 0.6;   % Dolní práh jako 60 % horního prahu
for i = 1:numElectrodes
    if i == idx_P5 || i == idx_P6
        continue; % Přeskočíme P5 a P6
    end
    fprintf('Maximální zatížení pro elektrodu %s: %.3f\n', label{i}, max_zatizeni(i));

    sig = envelopes_smooth(i, :);
    segments = zeros(numSegments, segmentLength);

    for j = 1:numSegments
        t0 = intervals(j, 1);
        t1 = intervals(j, 2);
        segments(j, :) = sig(t0+1:t1);  % výřez signálu
    end

    mean_seg = mean(segments, 1);
    all_segments{i} = segments;
    mean_segments{i} = mean_seg;

    threshold_up = upper_threshold_factor * max(mean_seg);
    threshold_down = lower_threshold_factor * threshold_up;

    y = zeros(1, length(mean_seg));
    y_old = 0;
    for j = 2:length(mean_seg)
        if y_old == 0
            y(j) = mean_seg(j) > threshold_up;
        else
            y(j) = mean_seg(j) > threshold_down;
        end
        y_old = y(j);
    end
    binary_cycles{i} = y;
    active_segments = find(diff([0 y 0]));

    figure;
    hold on;

    % Segmenty (modré)
    h1 = plot(time_axis, segments', 'Color', [0.4, 0.4, 1]);

    % Průměrná obálka (červeně)
    h2 = plot(time_axis, mean_seg, 'r', 'LineWidth', 2);
    % Čára pro maximální zatížení z měření M2
    h6 = yline(max_zatizeni(i), '-.', 'LineWidth', 1.5, ...
           'Color', [1 0.5 0], ...
           'DisplayName', 'Maximální zatížení (M2)');

    % Prahy
    h3 = yline(threshold_up, '--k', 'LineWidth', 1);
    h4 = yline(threshold_down, ':k', 'LineWidth', 1);

    dummy_rect = patch(nan, nan, [0.2 0.8 0.2], ...
                       'LineStyle', '--', 'EdgeColor', [0.2 0.8 0.2], ...
                       'FaceColor', 'none', 'LineWidth', 2);

    h5 = [];
    for k = 1:2:length(active_segments)-1
        x_start = time_axis(active_segments(k));
        x_end = time_axis(active_segments(k+1));

        segment_indices = active_segments(k):active_segments(k+1);
        segment_signal = mean_seg(segment_indices);
        peak_height = max(segment_signal);

        % Maxima
        h5(end+1) = plot(time_axis(segment_indices(segment_signal == peak_height)), ...
                         peak_height, 'ko', 'MarkerFaceColor', 'k');

        % Obdélník
        rectangle('Position', [x_start, 0, x_end - x_start, peak_height], ...
                  'EdgeColor', [0.2, 0.8, 0.2], ...
                  'LineWidth', 2, 'LineStyle', '--');
    end

    title(['Segmenty a průměr - ' label{i}]);
    xlabel('Čas [s]');
    ylabel('Amplituda');
    grid on;

    if ~isempty(h5)
        legend([h1(1), h2, h6, h3, h4, h5(1), dummy_rect], ...
       {'Jednotlivé segmenty', ...
        'Průměrná obálka', ...
        'Maximální zatížení (M2)', ...
        'Horní práh', ...
        'Dolní práh', ...
        'Maxima v aktivních úsecích', ...
        'Aktivní segmenty'}, ...
       'Location', 'northeastoutside');

    else
        legend([h1(1), h2, h6, h3, h4, h5(1), dummy_rect], ...
       {'Jednotlivé segmenty', ...
        'Průměrná obálka', ...
        'Maximální zatížení (M2)', ...
        'Horní práh', ...
        'Dolní práh', ...
        'Maxima v aktivních úsecích', ...
        'Aktivní segmenty'}, ...
       'Location', 'northeastoutside');

    end
end

%



reference_index = 2;
intervals = [
     0,     9300;
  9405,   18705;
 17943,   27243;
 25634,   34934;
 34738,   44038;
 44475,   53775;
 53931,   63231;
 62329,   71629;
 71078,   80378;
 80534,   89834;
 89849,   99149;
 99162,  108462;
108477, 117777;
117369, 126669;
126472, 135772
];


% Základní nastavení
numElectrodes = size(envelopes_smooth, 1);  % mělo by být 8
numSegments = size(intervals, 1);
segmentLength = intervals(1, 2) - intervals(1, 1);

% Vytvoříme časovou osu pro segmenty
time_axis = (0:segmentLength - 1) / fs;  % čas v sekundách

% Uložení výsledků
all_segments = cell(numElectrodes, 1);
mean_segments = cell(numElectrodes, 1);

% Najdeme indexy v poli label
idx_P3A = find(strcmp(label, 'PP2A'));
idx_P3B = find(strcmp(label, 'PP2B'));
idx_P1A = find(strcmp(label, 'PP1A'));
idx_P1B = find(strcmp(label, 'PP1B'));

% Zprůměrujeme obálky
envelopes_smooth(idx_P3A, :) = (envelopes_smooth(idx_P3A, :) + envelopes_smooth(idx_P3B, :)) / 2;
envelopes_smooth(idx_P1A, :) = (envelopes_smooth(idx_P1A, :) + envelopes_smooth(idx_P1B, :)) / 2;

% Přejmenujeme v label
label{idx_P3A} = 'PP2';
label{idx_P1A} = 'PP1';

idxs_to_remove = sort([idx_P3B, idx_P1B], 'descend');
for idx = idxs_to_remove
    envelopes_smooth(idx, :) = [];
    label(idx) = [];
end

numElectrodes = size(envelopes_smooth, 1);
for i = 1:numElectrodes
    if i == idx_P5 || i == idx_P6
         continue; 
    end

    sig = envelopes_smooth(i, :);
    segments = zeros(numSegments, segmentLength);

    for j = 1:numSegments
        t0 = intervals(j, 1);
        t1 = intervals(j, 2);
        segments(j, :) = sig(t0+1:t1);  % výřez signálu
    end

    mean_seg = mean(segments, 1);

    % Uložení
    all_segments{i} = segments;
    mean_segments{i} = mean_seg

    figure;
    hold on;
    
    % Vykreslení jednotlivých segmentů (modře)
    for j = 1:numSegments
        h_segments(j) = plot(time_axis, segments(j, :), 'Color', [0.4, 0.4, 1]);
    end
    
    % Vykreslení průměrné obálky (červeně)
    h_mean = plot(time_axis, mean_seg, 'r', 'LineWidth', 2);
    
    title(['Segmenty a průměr - ' label{i}]);
    xlabel('Čas [s]');
    ylabel('Amplituda');
    
    legend([h_segments(1), h_mean], {'Jednotlivé segmenty', 'Průměrná obálka'});
    
    grid on;

end
colors = lines(numElectrodes);
example_mean = mean_segments{find(~cellfun(@isempty, mean_segments), 1)};
segmentLength = length(example_mean);
time_axis = (0:segmentLength - 1) / fs;  % čas v sekundác
figure;
hold on;
for i = 1:numElectrodes
    electrode_name = label{i};

    if ismember(electrode_name, {'PP3', 'ZP3'})
        continue;
    end

    mean_seg = mean_segments{i};

    if strcmp(electrode_name, 'PP2')
        plot(time_axis, mean_seg, 'r', 'LineWidth', 2.5); 
    else
        plot(time_axis, mean_seg, 'Color', colors(i, :), 'LineWidth', 1.2);
    end
end

title('Průměrné obálky všech elektrod (s PP2 jako referencí)');
xlabel('Čas [s]');
ylabel('Amplituda');
legend_entries = label(~ismember(label, {'PP3', 'ZP3'}));
legend(legend_entries, 'Location', 'northeastoutside');
grid on;

%


colors = lines(length(label));
example_mean = mean_segments{find(~cellfun(@isempty, mean_segments), 1)};
segmentLength = length(example_mean);
time_axis = (0:segmentLength - 1) / fs;  % čas v sekundách
% Inicializace seznamu pro posunuté odhady
left_estimates = {};       % pro posuny dopředu
left_estimates_back = {};  % pro posuny dozadu
legend_entries = [];            % zde se uloží handles všech křivek
legend_labels = {};             % zde se uloží popisky do legendy


figure;
hold on;

for i = 1:length(mean_segments)
    if i > length(label)
        continue;
    end

    if ismember(label{i}, {'PP3', 'ZP3'})
        continue;
    end

    seg = mean_segments{i};

    if strcmp(label{i}, 'PP2')
        h = plot(time_axis, seg, 'r', 'LineWidth', 2.5);  
    else
        h = plot(time_axis, seg, 'Color', colors(i,:), 'LineWidth', 1.2);
    end
    % Uložení do legendy
    legend_entries(end+1) = h;
    legend_labels{end+1} = label{i};
end

% Najdeme indexy podle nových jmen
idx_P3 = find(strcmp(label, 'PP2'));
idx_L3 = find(strcmp(label, 'PL2'));
idx_P1 = find(strcmp(label, 'PP1'));
idx_P4 = find(strcmp(label, 'ZP2'));

% Získání signálů
P3 = mean_segments{idx_P3};
L3 = mean_segments{idx_L3};
P1 = mean_segments{idx_P1};
P4 = mean_segments{idx_P4};
disp(mean_segments)

% Výpočet časového posunu pomocí korelace
[xc, lags] = xcorr(L3, P3);  
[~, idx_max] = max(xc);
lag_samples = lags(idx_max);  % zpoždění v počtu vzorků

fprintf('Zpoždění mezi PP2 a PL2: %d vzorků (%.3f s)\n', lag_samples, lag_samples / fs);


L1_est = P1; 
L4_est = P4;

time_axis_shifted = time_axis + lag_samples / fs;

time_axis_shifted_neg = time_axis - lag_samples / fs;

left_estimates{end+1} = struct('label', 'Odhad PL1', 'time', time_axis_shifted, 'data', L1_est, 'color', [0 0.6 0]);
left_estimates{end+1} = struct('label', 'Odhad ZL2', 'time', time_axis_shifted, 'data', L4_est, 'color', [0.6 0 0.6]);

left_estimates_back{end+1} = struct('label', 'Odhad PL1', 'time', time_axis_shifted_neg, 'data', L1_est, 'color', [0 0.6 0]);
left_estimates_back{end+1} = struct('label', 'Odhad ZL2', 'time', time_axis_shifted_neg, 'data', L4_est, 'color', [0.6 0 0.6]);


for i = 1:length(left_estimates)
    h = plot(left_estimates{i}.time, left_estimates{i}.data, '--', ...
         'Color', left_estimates{i}.color, 'LineWidth', 1.5);
    legend_entries(end+1) = h;
    legend_labels{end+1} = left_estimates{i}.label;
end


for i = 1:length(left_estimates_back)
    plot(left_estimates_back{i}.time, left_estimates_back{i}.data, '--', ...
         'Color', left_estimates_back{i}.color, 'LineWidth', 1.2);
end



title('Průměrné obálky všech elektrod (včetně odhadované levé nohy)');
xlabel('Čas [s]');
ylabel('Amplituda');
grid on;

legend(legend_entries, legend_labels, 'Location', 'northeastoutside');
xlim([0,12])
%Vykreslení všech průměrných obálek a výpočet aktivních úseků
valid_idx = ~cellfun(@isempty, mean_segments);
mean_segments = mean_segments(valid_idx);
label = label(valid_idx);

colors = lines(length(label));
example_mean = mean_segments{find(~cellfun(@isempty, mean_segments), 1)};
segmentLength = length(example_mean);
time_axis = (0:segmentLength - 1) / fs;

AVERAGE = mean_segments;
AVERAGE{end+1} = L1_est;
AVERAGE{end+1} = L4_est;

% Aktualizace labelů
label{end+1} = 'PL1 (odhad)';
label{end+1} = 'ZL2 (odhad)';

AVERAGE{end+1} = L1_est;
label{end+1} = 'PL1 (zpět)';
AVERAGE{end+1} = L4_est;
label{end+1} = 'ZL2 (zpět)';

for i = 1:length(AVERAGE)
    fprintf('AVERAGE{%d} - %s - velikost: %s\n', ...
        i, label{i}, mat2str(size(AVERAGE{i})));
end


disp(label)
numElectrodes = length(AVERAGE);

figure;
hold on;

% Inicializace aktivních úseků
active_times = cell(length(AVERAGE), 1);
legend_entries = [];
legend_labels = {};

for i = 1:length(AVERAGE)
    if i > length(label) || isempty(AVERAGE{i}) || any(strcmp(label{i}, {'PP3', 'ZP3'}))
        continue;
    end
    disp(label(i))

    avg_envelope = AVERAGE{i};
    num_samples = length(avg_envelope);

    if contains(label{i}, '(zpět)')
        local_time = time_axis - lag_samples / fs;
    elseif contains(label{i}, '(odhad)')
        local_time = time_axis + lag_samples / fs;
    else
        local_time = time_axis;
    end


    % Vykreslení
    if strcmp(label{i}, 'PP2')
        plot(local_time, avg_envelope, 'r', 'LineWidth', 2.5, 'DisplayName', 'PP2');
    elseif strcmp(label{i}, 'PL1 (odhad)')
    plot(local_time, avg_envelope, '--', 'Color', [0 0.6 0], 'LineWidth', 1.5, ...
         'DisplayName', 'Odhad PL1');
    elseif strcmp(label{i}, 'PL1 (zpět)')
        plot(local_time, avg_envelope, '--', 'Color', [0 0.6 0], 'LineWidth', 1.2, ...
             'HandleVisibility', 'off');
    
    elseif strcmp(label{i}, 'ZL2 (odhad)')
        plot(local_time, avg_envelope, '--', 'Color', [0.6 0 0.6], 'LineWidth', 1.5, ...
             'DisplayName', 'Odhad ZL2');
    elseif strcmp(label{i}, 'ZL2 (zpět)')
        plot(local_time, avg_envelope, '--', 'Color', [0.6 0 0.6], 'LineWidth', 1.2, ...
             'HandleVisibility', 'off');
    else
        plot(local_time, avg_envelope, 'Color', colors(i,:), 'LineWidth', 1.2, ...
             'DisplayName', label{i});
    end

    threshold_up = upper_threshold_factor * max(avg_envelope);
    threshold_down = lower_threshold_factor * threshold_up;

    y = zeros(1, num_samples);
    y_old = 0;
    for j = 2:num_samples
        if y_old == 0
            y(j) = avg_envelope(j) > threshold_up;
        else
            y(j) = avg_envelope(j) > threshold_down;
        end
        y_old = y(j);
    end

    active_segments = find(diff([0 y 0]));
    times = [];
    for k = 1:2:length(active_segments)-1
        if active_segments(k+1) > num_samples
            continue;
        end
        x_start = local_time(active_segments(k));
        x_end = local_time(active_segments(k+1));
        times = [times; x_start, x_end];
    end

    active_times{i} = times;
  
    for k = 1:size(times,1)
        x_start = times(k,1);
        x_end = times(k,2);
        y_max = max(avg_envelope) * 1.05;  % trochu nad signál
    
        % Vykreslení horní a dolní čáry obdélníku
        plot([x_start x_end], [y_max y_max], 'g--', 'LineWidth', 1.2, 'HandleVisibility', 'off');
        plot([x_start x_end], [0 0], 'g--', 'LineWidth', 1.2, 'HandleVisibility', 'off');
        
        % Volitelně: svislé hrany (levá + pravá)
        plot([x_start x_start], [0 y_max], 'g--', 'LineWidth', 1.2, 'HandleVisibility', 'off');
        plot([x_end x_end], [0 y_max], 'g--', 'LineWidth', 1.2, 'HandleVisibility', 'off');
    end

end

%Výpis aktivních segmentů
for i = 1:length(AVERAGE)
    if isempty(active_times{i})
        continue;
    end
    fprintf('Elektroda %s:\n', label{i});
    disp(array2table(active_times{i}, 'VariableNames', {'Start_sec', 'End_sec'}));
end

% Dokončení grafu
title('Průměrné obálky všech elektrod (včetně odhadované levé nohy)');
xlabel('Čas [s]');
ylabel('Amplituda');
grid on;
legend('show', 'Location', 'northeastoutside');
xlim([0 12])

%




electrode_col = {};
start_col = [];
end_col = [];

for i = 1:numElectrodes
    if isempty(active_times{i})
        continue;
    end

    times = active_times{i};
    mask = times(:,1) >= 0 & times(:,2) <= 12;
    times = times(mask, :);
    if isempty(times)
        continue;
    end

    clean_label = erase(label{i}, ' (zpět)');
    clean_label = erase(clean_label, ' (odhad)');
    n_segments = size(times, 1);
    names = repmat({clean_label}, n_segments, 1);

    electrode_col = [electrode_col; names];
    start_col = [start_col; times(:, 1)];
    end_col = [end_col; times(:, 2)];
end


active_segments_table = table(electrode_col, start_col, end_col, ...
    'VariableNames', {'Elektroda', 'Start_sec', 'End_sec'});
writetable(active_segments_table, 'aktivni_useky_M1_first.xlsx');

%

figure;
numRows = ceil(sqrt(numElectrodes - 2)); 
numCols = ceil((numElectrodes - 2) / numRows);

plot_i = 0;

for i = 1:numElectrodes
    if isempty(AVERAGE{i}) || isempty(active_times{i})
        continue;
    end

    if contains(label{i}, '(zpět)')
        continue; 
    end

    plot_i = plot_i + 1;
    subplot(numRows, numCols, plot_i);
    hold on;

    if contains(label{i}, 'PL1') || contains(label{i}, 'ZL2')
        local_time = time_axis + lag_samples / fs;
    else
        local_time = time_axis;
    end

    avg_envelope = AVERAGE{i};
    threshold_up = upper_threshold_factor * max(avg_envelope);
    threshold_down = lower_threshold_factor * threshold_up;

    for seg = 1:size(active_times{i}, 1)
        x1 = active_times{i}(seg, 1);
        x2 = active_times{i}(seg, 2);
        patch([x1 x2 x2 x1], [0 0 max(avg_envelope)*1.1 max(avg_envelope)*1.1], ...
              [0.9 0.9 0.9], 'EdgeColor', 'none', 'FaceAlpha', 0.5);
    end
    plot(local_time, avg_envelope, 'b', 'LineWidth', 1.5);

    zp_label = erase(label{i}, '(odhad)');
    zp_label = strtrim(zp_label);  
    zp_label_full = [zp_label ' (zpět)'];
    idx_zpet = find(strcmp(label, zp_label_full));

    if ~isempty(idx_zpet)
        avg_zpet = AVERAGE{idx_zpet};
        local_time_zpet = time_axis - lag_samples / fs;

        for seg = 1:size(active_times{idx_zpet}, 1)
            x1 = active_times{idx_zpet}(seg, 1);
            x2 = active_times{idx_zpet}(seg, 2);
            patch([x1 x2 x2 x1], [0 0 max(avg_zpet)*1.1 max(avg_zpet)*1.1], ...
                  [0.8 1 0.8], 'EdgeColor', 'none', 'FaceAlpha', 0.4);
        end

        plot(local_time_zpet, avg_zpet, '--g', 'LineWidth', 1.5);
    end


    title(erase(label{i}, ' (odhad)'));
    xlabel('Čas [s]');
    ylabel('Amplituda');
    grid on;
end

sgtitle('Aktivní segmenty s prahováním (včetně zpětného odhadu)');