% This script will verify that your code is working as you intended, by
% running it on a small subset (300 records) of the training data, then
% comparing the answers.txt file that you submit with your entry with
% answers produced by your code running in our test environment using
% the same records.
%
% In order to run this script, you should have downloaded and extracted
% the validation set into the directory containing this file.
%
%
% Written by: Chengyu Liu and Qiao Li January 20 2017 
%             chengyu.liu@emory.edu  qiao.li@emory.edu
%
% Last modified by:Na Liu April 7 2017
%                  nkuliuina@163.com
%

% clear all;
% close all;
clc

data_dir = [pwd filesep 'validation' filesep];   %获取validation（训练集）的文件目录
% data_dir = [pwd filesep 'training2017' filesep];
%% Add this directory to the MATLAB path.
addpath(pwd)

%% Check for previous files before starting validation procedure
answers = dir(['answers.txt']);
if(~isempty(answers))
    while(1)
        display(['Found previous answer sheet file in: ' pwd])
        cont = upper(input('Delete it (Y/N/Q)?','s'));
        if(strcmp(cont,'Y') || strcmp(cont,'N') || strcmp(cont,'Q'))
            if(~strcmp(cont,'Y'))
                display('Exiting script!!')
                return;
            end
            break;
        end
    end
    display('Removing previous answer sheet.')
    delete(answers.name);
end

%% Load the list of records in the validation set.
fid = fopen([data_dir 'RECORDS'],'r');
if(fid ~= -1)
    RECLIST = textscan(fid,'%s');
else
    error(['Could not open ' data_dir 'RECORDS for scoring. Exiting...'])
end
fclose(fid);
RECORDS = RECLIST{1};
N       = length(RECORDS);

%% Extract features ()
% stat_RR = zeros(N,13); d = zeros(N,1); C = zeros(N,1);
% pow = zeros(N,1); p_ratio = zeros(N,1);
% AFEv = zeros(N,1);OriginCount = zeros(N,1);IrrEv = zeros(N,1);PACEv = zeros(N,1);
% HOS = zeros(N,3); P = zeros(N,6);
% P_absence = zeros(N,1);f_presence = zeros(N,1);Noise = zeros(N,1);
% wevelet_power = zeros(N,13);
% 
% for i = 1:N
%     fname = RECORDS{i};
%     tic;
%     [d(i),C(i),stat_RR(i,:),pow(i),AFEv(i),OriginCount(i),IrrEv(i),PACEv(i),p_ratio(i),HOS(i,:),P(i,:),P_absence(i),f_presence(i),Noise(i),wevelet_power(i,:)] = featureExtract([data_dir fname]);
%     feature(i,:)=[d(i),C(i),stat_RR(i,:),pow(i),AFEv(i),OriginCount(i),IrrEv(i),PACEv(i),p_ratio(i),HOS(i,:),P(i,:),P_absence(i),f_presence(i),Noise(i),wevelet_power(i,:)];
%     feature(isnan(feature))=0;
% %  [stat_RR(i,:)]= featureExtract([data_dir fname]);
%  i
% end
%% Load the reference classification results ()
% % reffile = ['validation' filesep 'REFERENCE.csv'];
% reffile = ['training2017' filesep 'REFERENCE-v2.csv'];
% fid = fopen(reffile, 'r');
% if(fid ~= -1)
%     Ref = textscan(fid,'%s %s','Delimiter',',');
% else
%     error(['Could not open ' reffile ' for scoring. Exiting...'])
% end
% fclose(fid);
% 
% RECORDS = Ref{1};
% target  = Ref{2};
% N       = length(RECORDS);
%% 查看某类型波形 (())
% for n=1:N
%      switch target{n}
%         case 'N'
%             fname = RECORDS{n};
%             [tm,ecg,fs,siginfo]=rdmat(fname);
%             [ecg,wevelet_power] = fliter(ecg,'db5');
%             QRS=qrs_detect2(ecg,0.25,0.6,fs); 
%             mean_R=mean(ecg(QRS));
%             if length(QRS)<7|(QRS(end)-QRS(1))<length(ecg)/2|abs(mean_R)>2
%                QRS=findQRS(ecg,1);
%                if length(QRS)<7|(QRS(end)-QRS(1))<length(ecg)/2
%                    if QRS(1)>length(ecg)/2
%                        QRS=findQRS(ecg(1:QRS(2)),1);
%                    else
%                        QRS=findQRS(ecg(QRS(1):end),1);
%                    end
%                end
%             end
% %             QRS(abs(ecg(QRS))>2)=[];
%             RR=diff(QRS')/fs;
%             mean_R=mean(ecg(QRS));
%             if mean_R>0,else ecg=-ecg;end
%             plocs_1=[];
%             left = max(floor(QRS(2:end)-0.205*mean(RR)*fs),QRS(1:end-1));
%             right= min(ceil(QRS(2:end)-0.06*mean(RR)*fs),QRS(2:end));
%             num=sum(left>0);
%             for i=1:length(left)
%                 if left(i)<=0
%                 else
%                     [pks,locs]=findpeaks(ecg(left(i):right(i)),'MinPeakHeight',0.25*ecg(QRS(i+1)));
%                     [~,ind]=max(ecg(locs-1+left(i)));
%                     ploc=locs(ind)-1+left(i);plocs_1=[plocs_1,ploc];
%                 end
%             end
%             p_ratio=length(plocs_1)/num;
%             if p_ratio>0.2
%                 n
%                 close all
%                 plot(ecg);hold on;plot(QRS,ecg(QRS),'ro',plocs_1,ecg(plocs_1),'k*');title([fname,'  p=',num2str(p_ratio)]) 
%                 pause()
%             end
%      end
% end
           
%% Generate the trainingData and trainedModel ()
% Y = zeros(length(RECORDS),1);
% for n = 1:N
%     switch target{n}
%         case 'N'
%             Y(n)=1;
%         case 'A'
%             Y(n)=2;
%         case 'O'
%             Y(n)=3;
%         case '~'
%             Y(n)=4;
%     end
% end
% % trainingData = [d,C,stat_RR,pow,AFEv,OriginCount,IrrEv,PACEv,p_ratio,HOS,P,P_absence,f_presence,Noise,wevelet_power,Y]; 
% trainingData = [d,C,stat_RR,pow,AFEv,OriginCount,IrrEv,PACEv,p_ratio,HOS,P,P_absence,f_presence,Noise,Y];
% % trainingData=[feature,Y];
% % data4=stat_RR;
%%  Running on the validation set and obtain the score results
classifyResult = zeros(N,1);
total_time = 0;
fid=fopen('answers.txt','wt');
for i = 1:length(RECORDS)
    fname = RECORDS{i};
    tic;
    classifyResult(i) = challenge([data_dir fname]);

    % write the answer to answers.txt file
    fprintf(fid,'%s,%s\n',RECORDS{i},classifyResult(i));

    total_time = total_time+toc;
    fprintf(['---Processed ' num2str(i) ' out of ' num2str(length(RECORDS)) ' records.\n'])
end
fclose(fid);

averageTime = total_time/length(RECORDS);
fprintf(['Generation of validation set completed.\n  Total time = ' ...
    num2str(total_time) '\n  Average time = ' num2str(averageTime) '\n'])

fprintf(['Answer file created as answers.txt.\n  Processing completed.\n'])

fprintf(['Running score2017Challenge.m to get scores on your entry on the validation data in training set....\n'])


%% Scoring
score2017Challenge

fprintf(['Scoring complete.\n'])
while(1)
    display(['Do you want to package your entry for scoring?'])
    cont=upper(input('(Y/N/Q)?','s'));
    if(strcmp(cont,'Y') || strcmp(cont,'N') || strcmp(cont,'Q'))
        if(strcmp(cont,'Q'))
            display('Exiting!!')
            return;
        end
        break;
    end
end

if(strcmp(cont,'Y'))
    display(['Packaging your entry (excluding any subdirectories) to: ' pwd filesep 'entry.zip'])
    % Delete any files if they existed previously
    if (exist('entry.zip','file'))
        delete('entry.zip');
    end
    % This will not package any sub-directories !
    zip('entry.zip',{'*.m','*.c','*.mat','*.txt','*.sh'});
end
