% SKRIPT SLOUŽÍ K NAHRÁNÍ DAT ZÍSKANÝCH Z THEW
% POSTUPNĚ NAHRÁVÁ JEDNOLIVÉ SVODY EKG A PROVÁDÍ NA NICH
% VYHLAZENÍ POMOCÍ KUBICKÉHO SPLINU A PRVNÍ DERIVACI SIGNÁLU
% VÝSLEDNÝ SIGNÁL JE ULOŽEN VE FORMÁTU .CSV


close all, clc, clear all

%%
[annot,text,~] = xlsread('ISCE_2018_LBBB_unblinded_full_dataset_corrected.xlsx');
load ('Annotation.mat')

for i = 1:size (text,1)

    
temp = char (text (i+1,3));    
name =[pwd,'\RAW\', temp,'.mat'];

load (name);
load ('Annotation.mat')

QRS_begin = annot(i,4);
QRS_end = annot(i,5);

Annotation = Annotation (1:1400);
Annotation(1:1400) = 'n';
Annotation(QRS_begin:QRS_end)= 'QRS';


    for j = 1:12
        
        data = [];
        patient = [];
        x = [];
        smooth = [];
        der_data = [];
        
        
        patient = s (:,j);
        
        if length (patient)> 1400
           patient = patient (1:1400);
        
        else
            temp = 1399 - length (patient);
            temp = patient ((length (patient) - temp) : length (patient))
            patient = [patient; temp]
        end
        
        x = 1:length(patient);
        smooth = csaps(x,patient,0.25) %smoothing with cubic spline
        der_data = diff(patient); %1. derivation
        
               
        smooth_data=smooth.coefs (:,4);
        smooth_data(end+1)= patient(end);
        der_data(end+1)=der_data(end);
        der_data=der_data';
       

        smooth_data = smooth_data';
        der_data = der_data';
        
        data = table;
        data{:,1} = x';
        data{:,2} = Annotation;
        data{:,3} = patient;
        data{:,4} = smooth_data';
        data{:,5} = der_data;
        
        data.Properties.VariableNames = {'index','annotation' 'signal' 'smooth' 'derivation'};
        
        tempi = int2str(i);
        tempj = int2str(j);
        name = ['THEW_data_',tempi,'_',tempj,'.csv']
                
        writetable(data,name,'Delimiter',';')
        clear data
        
    end
end