package org.physionet.challenge2011;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;


public class ChallengeEntry {

	public static final String DEBUGTAG = ChallengeEntry.class.toString();
	final static int FS= 500;					//Sampling Frequency
	final static int CH= 12;
	final static int MAX_RT= 220;				//Max expected beats in minutes
	final static int WIN=FS*10;
	final static double PKS_MIN=40/6;         		// Minimum number of expected peaks in 10s    
	final static int FRGT=(int) (FS*0.04);   		// Window for ignoring consecutive peaks 
	final static short [] W={1,1,1,-1,1,1,-1,-1,1,1,1,1}; // Weights for each channel
	final static double PK_TH=500; 		// Peak value hardcoded based on sample data
	static short [] sum = new short[WIN]; //Array for storing summed channel data
	
	//Define Quality values (could also be defined as enum...)
	final static int INIT=0;
	final static int GOOD = 0;
	final static int BAD =  1;
	short[] data=new short[WIN*CH];
	
	synchronized public int get_result(InputStream iFile, final ECG_MetaData m_MetaData) throws IOException {
		ObjectInputStream in = new ObjectInputStream(iFile);
		try {
			data = (short[])in.readObject();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		int result=INIT;  	// Set initial result 
		int pks= 0; 				// Number of BEATS detected
 		double pk_memory=0; 	// Memory of last peak
 		double PKS_MAX=( MAX_RT- (m_MetaData.age+1) )/6;         	// Max number of expected peaks in 10s
 		int index=0;
 		while ( index < WIN) {
			//Load summed data into array 
			sum[index]= 0; //Initialize
			for(int ch=0;ch<CH;ch++){
				sum[index] += W[ch]*data[index*CH + ch];
			}		
			if((pk_memory > FRGT) && sum[index] > PK_TH){
				//If peak is in acceptable range, increment count and reset memory
				pks++; 
				pk_memory=0;
			}else{ 
				//Allow memory to forget past peak
				pk_memory++;
			}
			index++;		
			//Output quality based on number of measured peaks, and age
			if(pks > PKS_MAX || pks < PKS_MIN){
				//Bad quality
				result=BAD;
			}else{
				//Normal number of beats, so assume good quality
				result=GOOD;
			}
		}

		//clean-up
		iFile.close();	
		return result;

	}

}
