%This script will generate the validation set that will be used for
%cross-checking by the PhysionNet servers. You should have the training
%set located at the subdirectory ./challenge/2014/set-p/
% (or .\challenge\2014\set-p\ in Windows).
%
%Althought this script can be run from MATLAB, it is best to have it run on
%an Octave 3.6.2 for the generation of final validation set. This script
%needs to be run from its current directory (sample-octave-entry).
%
%
% Written by Ikaro Silva January 21, 2014.
%         Last Modified: February 11, 2014
%
%

clear all;close all;clc
cur_dir=pwd;
ans_dir=[cur_dir filesep 'challenge' filesep '2014' filesep 'set-p'];

%Add the sample entry directory to the current path so we can call
%'challenge.m' from other directories, but don't save the path permanently.
addpath(cur_dir)

if(exist('OCTAVE_VERSION'))
   more off %this seems necessary in order to get back the screen in Octave
end

%Check for previous files before starting test
qrs=dir([ans_dir filesep '*.qrs']);
if(~isempty(qrs))
    while(1)
        display(['Found previous QRS files in:' ans_dir])
        cont=input('Delete them all (Y/N/Q)?','s');
        if(strcmp(cont,'Y') || strcmp(cont,'N') || strcmp(cont,'Q'))
            if(strcmp(cont,'Q'))
                display('Exiting script!!')
                return;
            end
            break;
        end
    end
    if(strcmp(cont,'Y'))
        display('Removing previous generated files.')
        for i=1:length(qrs)
            delete([ans_dir filesep qrs(i).name]);
        end
    end
end

fprintf('Generating validation set, please wait...\n')
%Start the validation
training=dir([ans_dir filesep '*.dat']);
if(length(training) ~= 100)
    warning(['Training data does not have 100 records! Training set location: ' ans_dir filesep])
    warning(['Download training set at: http://www.physionet.org/physiobank/database/challenge/2014/set-p.zip'])
    error('Cannot continue because training set does not have 100 records.')
end

N=length(training); %This should always be 100, but we display it as an extra double check.
try
    cd(ans_dir)
    total_time=0;
    for i=1:N
        fname=training(i).name;
        tic;
        %Remove .dat extension from file name
        challenge(fname(1:end-4));
        total_time=total_time+toc;
        if(~mod(i,10))
            fprintf(['---Annotated ' num2str(i) ' out of ' num2str(N) ' records.\n'])
        end
    end
    averageTime = total_time/N;
    cd(cur_dir);
    fprintf(['Generation of validation set completed !! Total time= ' ...
        num2str(total_time) ' average time= ' num2str(averageTime) '\n'])
catch
    cd(cur_dir);
    error(lasterr)
end

fprintf(['To  package your entry into a valid entry.zip submission file, on unix systems run : \n'])
fprintf(['\tzip -r entry.zip . -x ./challenge/2014/set-p/*.dat -x ./challenge/2014/set-p/*.hea \n'])





