#include "defs.h"
#include <stdio.h>
#include "colorlist.h"
#include "imageio.h"
#include "imagemath.h"
#ifdef USE_DEBUG
#include "time.h"
#endif
#ifdef USE_CLUSTER
#include "cluster.h"
#endif

int differ(ImagePtr *dest,ImagePtr imsource1, ImagePtr imsource2,struct colorlist* excludelist) {
/*Creates a Difference map between the 2 source images and
  stores it into the destination image*/

   ImagePtr imdest;		/*VarPointers to the Image Data*/
   int t,tt,actual,sum,alpha;	/*Several integers*/
   int r1,g1,b1,x,y;		/*Even more integers*/
   int r2,g2,b2;
   int color[256];		/*Some sort of Color Map*/

#ifdef USE_DEBUG
   clock_t starttime;
   starttime=clock();
   fprintf(stderr,"Running difference calculation... \n");
#endif

   x=widthim(imsource1);
   y=heightim(imsource1);
   if (widthim(imsource2)<x) x=widthim(imsource2);
   if (heightim(imsource2)<y) y=heightim(imsource2);
   /*calculate size safe*/

   imdest   = createim(x,y);
   *dest=imdest;
   /*We create a destination image the size of the source*/
   /*and give its adress back*/

   t=0;
   while (t<256) {
      color[t]=collorallocateim(imdest,t,t,t);
      t++;
   }
   /*We create some sort of 256 colors b/w colormap for the destination*/

   sum=0;
   tt=0;
   #ifdef USE_CLUSTER
      cluster_split();
      /*time to split up the work */
      tt=cluster_split_min(0,y);
      y=cluster_split_max(0,y);
      #ifdef USE_DEBUG
         fprintf(stderr,"process(%i): doing from %i till %i ...\n",pid(),tt,y);
      #endif
   #endif
   while (tt<y) {
      t=0;
      while (t<x) {
         r1=pixelredim(imsource1,t,tt);
	 g1=pixelgreenim(imsource1,t,tt);
	 b1=pixelblueim(imsource1,t,tt);
         r2=pixelredim(imsource2,t,tt);
	 g2=pixelgreenim(imsource2,t,tt);
	 b2=pixelblueim(imsource2,t,tt);

         actual=pixelbrightcim(r1,g1,b1)-pixelbrightcim(r2,g2,b2);
	 if (actual<0) actual=-actual;
	 alpha=colorlist_getvalue(excludelist,r1,g1,b1);
	 alpha*=colorlist_getvalue(excludelist,r2,g2,b2);
	 actual=(actual*alpha)/65025;

	 sum+=actual;
	 drawpixelim(imdest,t,tt,color[actual]);
	 t++;
      }
      tt++;
   }
   /*Main Working stuff. this is importnat!
     Go through every pixel of the 1st image and compare it with the 2nd image.
     Multiply the alpha values of these pixel
     (calculated from color exclude list)
     to check if those pixels are to be counted less
     Then save the positive result as grey value in
     the corresponding pixel of the destination image*/

#ifdef USE_CLUSTER
   sum=cluster_sync_add(sum);
   processsyncim(imdest,heightim(imsource1));
   cluster_regroup();
   /*re combine execution*/
#endif

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

}


