#include "presentation.h"
#include <math.h>
#include <stdio.h>

#define DOWNSAMPLE 2

void ExtractPresentation::Init(int xsize, int ysize)
{
	width = xsize/DOWNSAMPLE;
	height = ysize/DOWNSAMPLE;
	if (prevImage!=NULL) 
		cvReleaseImage(&prevImage);
	prevImage = cvCreateImage(cvSize(width, height), 8, 1);
	if (work!=NULL) 
		cvReleaseImage(&work);
	work = cvCreateImage(cvSize(width, height), 8, 1);
}

bool ExtractPresentation::CalcDifference(IplImage *image, float Threshold)
{
	const int cw = 5;
	const int ch = 5;
	int dw = image->width  / cw;
	int dh = image->height / ch;
	IplImage *tmpImage = cvCreateImage(cvSize(image->width, image->height)/*cvGetSize(image)*/, 8, 1);
	cvCvtColor( image, tmpImage, CV_BGR2GRAY );
	cvPyrDown(tmpImage, work, CV_GAUSSIAN_5x5);
	cvReleaseImage(&tmpImage);
	//////////////////////////// compare images ///////////////////////
	double Diff = 0;
	int arr[cw*ch];						// array of pixel sum for image parts
	memset(arr,0,sizeof(int)*cw*ch);
	for (int j=0; j<height; j++)
	{
      char *data1 = prevImage->imageData + prevImage->widthStep*j;
	  char *data2 = work->imageData + work->widthStep*j;
	  for (int i=0; i<width; i++)
	  {
		  int val1 = (unsigned char)*(data1);// + *(data1+1);
		  int val2 = (unsigned char)*(data2);// + *(data2+1);
		  Diff = fabs(double(val1-val2));
		  // if color difference is bigger than given threshold
		  if (Diff>Threshold) arr[i/dw + (j/dh)*cw]+=1;
		  data1+=prevImage->nChannels;
		  data2+=work->nChannels;
	  }
	}
	int whole = 0;
	// count how many parts of image exceed the 0.5% of the change inside the part
	for (int i=0; i<cw*ch; i++)
	{
		if (arr[i]>0.003*dw*dh) whole++;
		if (i%cw==0) printf("\n");
		printf ("%d  ",arr[i]);
	}
        printf("\n");
	cvCopyImage(work, prevImage);
	printf("Number of changes in image %d\n", whole);
	if (whole>cw*ch*0.2)
		return true;
	return false;
}