#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 enhance(ImagePtr* dest, ImagePtr imsource,
	int value1, int value2, int value3) {
/*Greatly enhances the edges (object outlines) of source
  and saves this into dest, uses value/100 pixels for
  edge calculation around position, uses value2/100
  as multiplicator for enhance result
  value3 is a quality index which affects
  destination image size in percent, maximum is 100*/

   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 enhance with %.2f pixels times %.2f with %i%% quality...\n",
      value1/100.,value2/100.,value3);
#endif


   imdest   = createim(widthim(imsource)*value3/100,
   		heightim(imsource)*value3/100);
   *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*value1/100);
   x2=((256*widthim(imsource))-nx2)/x;
   y=heightim(imdest);
   ny2=(256*value1/100);
   y2=((256*heightim(imsource))-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=value2*diffscalepixelim(imsource,t2,tt2,t2+nx2,tt2+ny2)/100;
	 if (actual>255) actual=255;
	 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 "edgyness" (average difference
     of all scource area pixels to their average breightness)
     value times value2/100
     This way we are outlining 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*/

}


