%	OVERVIEW:
%       This demonstration analyzes a segment of data collected in the 
%       intensive care unit (ICU) which contains ECG, ABP, and PPG signals 
%
%   OUTPUT:
%       HRV Metrics exported to .cvs files
%
%   DEPENDENCIES & LIBRARIES:
%       https://github.com/cliffordlab/PhysioNet-Cardiovascular-Signal-Toolbox
%   REFERENCE: 
%       Vest et al. "An Open Source Benchmarked HRV Toolbox for Cardiovascular 
%       Waveform and Interval Analysis" Physiological Measurement (In Press), 2018. 
%	REPO:       
%       https://github.com/cliffordlab/PhysioNet-Cardiovascular-Signal-Toolbox
%   ORIGINAL SOURCE AND AUTHORS:     
%       Giulia Da Poian   
%	COPYRIGHT (C) 2018 
%   LICENSE:    
%       This software is offered freely and without warranty under 
%       the GNU (v3 or later) public license. See license file for
%       more information
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

clear; clc; close all;

run(['..' filesep 'startup.m'])

% Remove old files generated by this demo
OldFolder = [pwd,filesep, 'OutputData', filesep, 'ResultsICU'];
if exist(OldFolder, 'dir')
    rmdir(OldFolder, 's');
    fprintf('Old Demo Folder deleted \n');
end

HRVparams = InitializeHRVparams('demoICU'); % include the project name
HRVparams.poincare.on = 0; % Pinocare analysis off for this demo
HRVparams.DFA.on = 0; % DFA analysis off for this demo
HRVparams.MSE.on = 0; % MSE analysis off for this demo
HRVparams.HRT.on = 0; % HRT analysis off for this demo


[subjectIDs,filesTBA] = GenerateListOfFilesTBA(HRVparams.ext,HRVparams.readdata,0);

idx = find(strcmp(subjectIDs,'TestICUdata'));

i_patient = idx;

% 1. Load Raw Patient Data (ECG Waveform)
load(filesTBA{i_patient});

% 2. Analyze data using HRV PhysioNet Cardiovascular Signal Toolbox
[~, resFilename] = Main_HRV_Analysis(signal(:,1),[],'ECGWaveform',...
    HRVparams,subjectIDs(i_patient),[],[],signal(:,5),'PPG',signal(:,3),'ABP');

% 3. Load annotations ans SQI for plot
AnnFile = strcat(HRVparams.writedata, filesep, 'Annotation', filesep, ...
                                                    subjectIDs{i_patient});
jqrs_ann = read_ann(AnnFile,'jqrs');
[~,~,sqijw] = read_ann(AnnFile,'sqijw'); % SQI is x100 to be stored

ppg_ann = read_ann(AnnFile,'ppg');
qppg(signal(:,5),HRVparams.Fs);
[~,ppgsqi,ppgNumSqi] = read_ann(AnnFile,'sqippg');

abpann = read_ann(AnnFile,'abpm');
features =  abpfeature(signal(:,3), abpann, HRVparams.Fs);
[BeatQ, goodbeats] = jSQI(features, abpann, signal(:,3));

% 5. Plotting
HRVparams.gen_figs = 1;
if HRVparams.gen_figs
    % ECG
    Plot_SignalDetection_SQI(time, signal(:,1), jqrs_ann, sqijw'./100,'ECG')
    
    % ABP
    Plot_SignalDetection_SQI(time, signal(:,3), abpann, double(~BeatQ(:,1))','ABP')
    
    % RESP
    figure(88)
    plot(time,signal(:,6));
    title('Respiration')
    
    % PLETH	
    Plot_SignalDetection_SQI(time, signal(:,5), ppg_ann, ppgNumSqi'./100,'PPG')

end

% 6. Pulse Transit Time
ptt = pulsetransit(jqrs_ann, abpann);

% 7. Plot BP vs PTT
syst = features(1:length(ptt),2);
if HRVparams.gen_figs
    figure(22)
    plot(syst,ptt(:,3)./HRVparams.Fs,'o');
    xlabel('BP (mmHg)'); ylabel('PTT (s)');
    title('Pulse Transit Time - BP vs PTT (ABP - QRS)')
	
end


% 8. Compare generated output file with the reference one
        
currentFile = strcat(HRVparams.writedata, filesep, resFilename.HRV, '.csv');
referenceFile = strcat('ReferenceOutput', filesep, 'ICU_HRV_allwindows.csv');
testHRV = CompareOutput(currentFile,referenceFile);

if testHRV
    fprintf('** DemoRawDataICU: TEST SUCCEEDED ** \n ')
     fprintf('A file named %s.csv \n has been saved in %s \n', ...
    resFilename.HRV, HRVparams.writedata);
else
    fprintf('** DemoRawDataICU: TEST FAILED ** \n')
end