% INPUTS:
% recordName: string specifying the record name to process
%
% OUTPUTS:
% classifyResult: integer value where
%                     N = normal rhythm
%                     A = AF
%                     O = other rhythm
%                     ~ = noisy recording (poor signal quality)
%
% To run your entry on the entire training set in a format that is
% compatible with PhysioNet's scoring enviroment, run the script
% generateValidationSet.m
%
% The challenge function requires that you have downloaded the challenge
% data 'training_set' in a subdirectory of the current directory.
%    http://physionet.org/physiobank/database/challenge/2017/
%
% This dataset is used by the generateValidationSet.m script to create
% the annotations on your training set that will be used to verify that
% your entry works properly in the PhysioNet testing environment.
%
%
% Version 1.0
%
%
% Written by: Pietro Bonizzi
%             pietro.bonizzi@maastrichtuniversity.nl
%             Joel Karel
%             joel.karel@maastrichtuniversity.nl
% licensed under simplified BSD license
function classifyResult = challenge(recordName)
%% read single lead ECG signal
classifyResult = 'N'; % default output normal rhythm
[tm,ecg,fs,siginfo]=rdmat(recordName);

load overallmodel
load noisemodel

%% find noise signals
nf=getNoiseFeatures(ecg);
% put it through a model
%load noisemodel  
try
    isnoise = predict(cmpctNoise,nf);
catch
    isnoise='~';
end
if(strcmp(isnoise,'~'))
    classifyResult = '~';
    return;
end

%% signal pre-processing
[B,A] = cheby2(3,20,[0.5/(fs/2) 100/(fs/2)]);
ecg = filtfilt(B,A,ecg);

QRS = findQRScomplexes(ecg,fs);

%% check whether signal is too noisy to extract parameters
if(length(QRS)< length(ecg)/fs*0.4)
    classifyResult='~';
    return;
end

%% extract parameters
[x,Parameters] = extractParameters(ecg,fs,QRS);

%% perform classification
% load Ensoble model
if((sum(isinf(x))==0)&&(sum(isnan(x))==0))
    %load model

    try
        classifyResult = predict(cmpctRus,x);
    catch
        classifyResult='~';
    end
else
    classifyResult='~';
end

if(isempty(classifyResult)||not(ischar(classifyResult)))
    classifyResult='~';
end
    
if(not(strcmp(classifyResult,'~') || strcmp(classifyResult,'A') || strcmp(classifyResult,'N') || strcmp(classifyResult,'O')))
    classifyResult='~';
end
