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

int blur(ImagePtr* dest, ImagePtr imsource, int value) {
/*blurs the pixels of source and saves this into dest,
  uses value/100 pixels for blur calculation around position*/

   ImagePtr imdest;		/*VarPointers to the Image Data*/
   int t,tt,actual,sum;		/*Several integers*/
   int x,y,x2,y2;
   long t2,tt2,nx2,ny2;
   int color[256];		/*Some sort of Color Map*/

#ifdef USE_DEBUG
   clock_t starttime;
   starttime=clock();
   fprintf(stderr,"Running blur with %.2f pixels...\n",
      value/100.);
#endif


   imdest   = createim(widthim(imsource),heightim(imsource));
   *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*/

   tt=0;
   tt2=0;
   sum=0;
   x=widthim(imdest);
   nx2=((256*value)/100);
   x2=((256*x)-nx2)/x;
   y=heightim(imdest);
   ny2=((256*value)/100);
   y2=((256*y)-ny2)/y;
   #ifdef USE_CLUSTER
      cluster_split();
      /*time to split up the work */
      tt=cluster_split_min(0,y);
      tt2=tt*y2;
      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;
      t2=0;
      while (t<x) {
         actual=scalepixelim(imsource,t2,tt2,t2+nx2,tt2+ny2);
	 sum+=actual;
         drawpixelim(imdest,t,tt,color[actual]);
	 t++;
         t2+=x2;
      }
      tt++;
      tt2+=y2;
   }
   /*Main Working stuff, this is important!
     Go through every pixel of the destination image and set
     its grey value to the average brightness of the source area
     size value/100.
     This way we are bluring all structures in the image.
     */

#ifdef USE_CLUSTER
   sum=cluster_sync_add(sum);
   processsyncim(imdest,heightim(imdest));
   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*/

}


