%{ 
    processPPG.m
    Krystof Sara <xsarak00@stud.feec.vutbr.cz> 2019-2020

    Funkce zodpovedna za zpracovani jasoveho signalu, jeho vyfiltrovani 
    a zobrazeni do grafu hlavniho okna projektu. Funkce predpoklada jiz 
    nacteny PPG signal spolecne s dalsimi atributy zaznamu ve strukture 
    'ui', tj.:
        ui.framez - PPG signal
        ui.frate  - vzorkovaci frekvence, FPS
%}

function [ui] = processPPG(ui)

%% Filtrace

half_fs = floor(ui.frate/2);

% FIR filtry PP a DP
b1 = fir1(10, [0.8/half_fs 3/half_fs], 'band'); a1 = 1;
b2 = fir1(15, 2/half_fs, 'low'); a2 = 1;

fil_fz = filtfilt(b1, a1, ui.framez).^2;
fil_fz = filtfilt(b2, a2, fil_fz);

%% Detekce peaku a vizualizace

[~, ui.peak_x] = findpeaks(fil_fz);

% Normalizace 
ui.framez = (ui.framez-min(ui.framez))/(max(ui.framez)-min(ui.framez));
fil_fz = (fil_fz-min(fil_fz))/(max(fil_fz)-min(fil_fz));

% Vizualizace
plot(ui.framez, 'g', 'LineWidth', 0.9, 'Parent', ui.plots(1));
hold(ui.plots(1), 'on')
plot(fil_fz, 'Parent', ui.plots(1));
hold(ui.plots(1), 'on')
plot(ui.peak_x, fil_fz(ui.peak_x), '*r', 'Parent', ui.plots(1));
xlim(ui.plots(1), [0 length(fil_fz)]);
legend(ui.plots(1), {'Surove PPG', 'Filtrovane PPG'}, 'Location', 'southeast');

%% Intervalova funkce

roz = diff(ui.peak_x);
ui.ppg_hr = 60./(roz/ui.frate);
ui.ppg_hr_value = round(mean(ui.ppg_hr(:)));

% Vizualizace
set(ui.text(1), 'String', sprintf('PPG TF\n  %.0f', ui.ppg_hr_value));
set(ui.text(1), 'Visible', 'on');
stem(ui.peak_x(1:end-1)/ui.frate, ui.ppg_hr, '*', 'Parent', ui.plots(2))
xlim(ui.plots(2), 'auto');
set(ui.push_history, 'String', 'Historie');

figure;
plot(ui.framez, 'g')
hold on
plot(fil_fz, 'b')
hold on
plot(ui.peak_x, fil_fz(ui.peak_x), '*r')

end