#include "defs.h"
#include <stdio.h>
#include <stdlib.h>
#include "imageio.h"
#include "patternlist.h"
#ifdef USE_DEBUG
#include "time.h"
#endif

struct patterntarget {
   int x;
   int y;
   int yield;
};

struct patterntarget findpattern(	ImagePtr imsource,
				struct pattern pattern,int x,int y,
				int width, int height )
{
/*Does a pattern search in imsource, searches for specific pattern around
  a given position*/

   int t,tt,x1,x2,y1,y2,actual;		/*Several integers*/
   int i,ii;
   int color[256];			/*Some sort of Color Map*/
   struct patterntarget returnval;	/*Obvious isnt it?*/
   struct pattern area;			/*area to check against*/

#ifdef USE_DEBUG
   clock_t starttime;
   starttime=clock();
   fprintf(stderr,"Running single pattern search around pos %i, %i...\n",x,y);
#endif

   area.brightness=(int*)malloc(sizeof(int[pattern.width*pattern.height]));
   area.width=pattern.width;
   area.height=pattern.height;
   /*Initialize Buffer for the pattern to check*/
   

   x1=x-width;
   if (x1<0) x1=0;
   x2=x+width;
   if (x2>widthim(imsource) - pattern.width) x2=widthim(imsource) - pattern.width;
   y1=y-height;
   if (y1<0) y1=0;
   y2=y+height;
   if (y2>heightim(imsource) - pattern.height) y2=heightim(imsource) - pattern.height;

   
   t=y1;
   returnval.yield=-1;
   while (t<y2) {
      tt=x1;
      while (tt<x2) {
         i=0;
	 while (i<pattern.height) {
	    ii=0;
	    while (ii<pattern.width) {
	       area.brightness[i*pattern.width+ii]=pixelbrightim(imsource,tt+ii,t+i);
	       ii++;
	    }
	    i++;
	 }
         /*Filled the pattern buffer, now trying for best match*/
	 actual=pattern_compare(&pattern,&area);
	 if (returnval.yield<0 || actual<returnval.yield) {
	    returnval.yield=actual;
	    returnval.x=tt;
	    returnval.y=t;
	 }
	 tt++;
      }
      t++;
  }

   free(area.brightness);

#ifdef USE_DEBUG
   fprintf(stderr," ... took  %.4f seconds!\n",(1.0 * (clock() - starttime) / CLOCKS_PER_SEC));
#endif

   return returnval;
  /*and we are finnished*/

}


