#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 resize(ImagePtr* dest, ImagePtr imsource, int value){
/*resize imsource by factor value % and saves the result in dest*/

   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 resize with %i percent ...\n",value);
#endif

   imdest   = createim(widthim(imsource)*value/100,
   		heightim(imsource)*value/100);
   *dest=imdest;
   /*We create a destination image twice 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);
   x2=256*widthim(imsource)/x;
   y=heightim(imdest);
   y2=256*heightim(imsource)/y;
   #ifdef USE_CLUSTER
      cluster_split();
      /*time to split up the work */
      tt=cluster_split_min(0,y);
      tt2=y2*tt;
      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;
      ny2=tt2+y2;
      while (t<x) {
         nx2=t2+x2;
	 actual=scalepixelim(imsource,t2,tt2,nx2,ny2);
	 sum+=actual;
         drawpixelim(imdest,t,tt,color[actual]);
         t2=nx2;
	 t++;
      }
      tt++;
      tt2=ny2;
   }
   /*Main Working stuff, this is important!
     Go through every pixel of the destination
     and set it to the average of the corresponding
     source regions grey value */

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

}


