#ifdef _CH_
#pragma package <opencv>
#endif

#ifndef _EiC
#include "cv.h"
#include "cvaux.h"
#include "highgui.h"
#endif

#include "feature.h"
#include <vector>
#include <math.h>

#include "edgeFeature.h"
#define eohbins 6

//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

edgeFeature::edgeFeature() {
	dominantOrientation=0;
	dominantOrientation2=-1;
}

edgeFeature::edgeFeature(int d) {
	dominantOrientation=d;
}

edgeFeature::edgeFeature(int d, int d2) {
	dominantOrientation=d;
	dominantOrientation2=d2;
}

edgeFeature::~edgeFeature() {

}

int edgeFeature::calcValue(IplImage *input, IplImage **bins, IplImage *red, IplImage *CumulativeIntensities) {
	//printf("widths = %i\n", scaleX);
	//float *integrals=new float[eohbins];
	
	//get 4 points for integral image calculation
	int Ax=offsetX;
	int Ay=offsetY;
	int Dx=width*scaleX + offsetX;
	int Dy=height*scaleY + offsetY;
	int Bx=Ax;
	int By=Dy;
	int Cx=Dx;
	int Cy=Ay;
	
	float A=((float*)(bins[dominantOrientation]->imageData + bins[dominantOrientation]->widthStep*Ay))[Ax];
	float B=((float*)(bins[dominantOrientation]->imageData + bins[dominantOrientation]->widthStep*By))[Bx];
	float C=((float*)(bins[dominantOrientation]->imageData + bins[dominantOrientation]->widthStep*Cy))[Cx];
	float D=((float*)(bins[dominantOrientation]->imageData + bins[dominantOrientation]->widthStep*Dy))[Dx];
	float sumDO=A+D-C-B;	//sum of dominant orientation

	float sumDO2=0;
	if (dominantOrientation2>-1) {
		A=((float*)(bins[dominantOrientation2]->imageData + bins[dominantOrientation2]->widthStep*Ay))[Ax];
		B=((float*)(bins[dominantOrientation2]->imageData + bins[dominantOrientation2]->widthStep*By))[Bx];
		C=((float*)(bins[dominantOrientation2]->imageData + bins[dominantOrientation2]->widthStep*Cy))[Cx];
		D=((float*)(bins[dominantOrientation2]->imageData + bins[dominantOrientation2]->widthStep*Dy))[Dx];
		sumDO2=A+D-C-B;
	}

	A=((float*)(CumulativeIntensities->imageData + CumulativeIntensities->widthStep*Ay))[Ax];
	B=((float*)(CumulativeIntensities->imageData + CumulativeIntensities->widthStep*By))[Bx];
	C=((float*)(CumulativeIntensities->imageData + CumulativeIntensities->widthStep*Cy))[Cx];
	D=((float*)(CumulativeIntensities->imageData + CumulativeIntensities->widthStep*Dy))[Dx];
	float totalSum=(float)(A+D-C-B);	//sum of all edge intensities in given region
	
	float ret=0;
	if (totalSum>0) {
		if (dominantOrientation2>-1) {
			ret=((sumDO+sumDO2)/totalSum)*10000;
		}else {
			ret=(sumDO/totalSum)*10000;	//multiply by 10000 to make integer (easier to sort, store)
		}	
	}

	return (int) ret;
}

#ifdef _EiC
main(1,"edgefeature.cpp");
#endif