function [classifyResult,QRS,ecg,AFEv,RR,qrs_amp_raw,QRSa,ATEv,OrgIdx,OriginCount,IrrEv,PACEv] = challengeAA(ecg,fs)
%
% Sample entry for the 2017 PhysioNet/CinC Challenge.
%
% 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: Chengyu Liu and Qiao Li January 20 2017
%             chengyu.liu@emory.edu  qiao.li@emory.edu
%
% Last modified by:
%
%

classifyResult = 0; % default output normal rhythm

%% AF determination
% [tm,ecg,fs,siginfo]=rdmat(recordName);

% d1 = designfilt('lowpassiir','FilterOrder',12, ...
%     'HalfPowerFrequency',0.1,'DesignMethod','butter');
% ecg = filtfilt(d1,ecg);
% windowSize = 30;
% N=60; sr = 1000;
% Wn = 800/sr;
% b1 = fir1(N,Wn,'low',hamming(N+1));
% ecg = filtfilt(b1,1,ecg);
% ecg=ecg(200:end);
% [QRS,sign,en_thres] = qrs_detect2(ecg',0.25,0.6,fs);
% [qrs_amp_raw,QRSa,delay]=pt(ecg,fs,0);

% polyNo=floor(length(ecg)/1000);
% [p,s,mu] = polyfit((1:numel(ecg))',ecg,polyNo);
% f_y = polyval(p,(1:numel(ecg))',[],mu);
% ecg = ecg - f_y; 
% [QRS,sign,en_thres] = qrs_detect2(ecg',0.25,0.6,fs);
QRS=findBestQRSnewPD(ecg);
%QRS=findBestQRSnewPD(ecg);
QRS=QRS(:)';
% [length(QRS),length(QRSa)]
% if length(QRS)<3
%     length(QRS)
%     length(QRSa)
% end
qrs_amp_raw=ecg(QRS);
QRSa=QRS;
if length(QRS)<6
    RR=diff(QRS')/fs;
    AFEv =0;ATEv=0;OrgIdx=0;
    IrrEv=0;PACEv=0;OriginCount=0;
else
    RR=diff(QRS')/fs;
    [AFEv,ATEv,OrgIdx,OriginCount,IrrEv,PACEv] = comput_AFEv(RR);
    if AFEv>1
        classifyResult = 1;
    end
end