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

int enlight(ImagePtr* dest, ImagePtr imsource,int value) {
/*Modifies the brightness of the source image
  and saves this into dest*/

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

#ifdef USE_DEBUG
   clock_t starttime;
   starttime=clock();
   fprintf(stderr,"Running enlighten with value %i...\n",value);
#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;
   sum=0;
   x=widthim(imdest);
   y=heightim(imdest);
   #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) {
         actual=pixelbrightim(imsource,t,tt)*value/100;
	 if (actual>255) actual=255;
         drawpixelim(imdest,t,tt,color[actual]);
	 sum+=actual;
	 t++;
      }
      tt++;
   }
   /*Main Working stuff, this is important!
     Go through every pixel of the source image and set the
     corrseponding pixel of the destination image to the
     corresponding grey-value of the source pixel modified
     by value percent. Value=20 means image gets 120% brightness.
     Simple routine, but could be useful for several things */

#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*/

}


