#include "defs.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "printtext.h"
#include "imageio.h"
#include "sectorlist.h"
#include "checkmove.h"
#include "arglist.h"
#ifdef USE_CLUSTER
#include "cluster.h"
#endif

int sectorX (char* sectorstring) {
   /*returns the x coordinate of a specified sectorstring*/
   int t,len;
   char* resultstring;

   if (sectorstring==NULL) return -1;
   resultstring=strdup(sectorstring);
   t=0;
   len=strlen(resultstring);
   while (t<len){
      if (resultstring[t]==',') {
         len=t;
	 resultstring[t]='\0';
      }
      t++;
   }
   t=arglist_integer(resultstring);
   free(resultstring);
   return t;
}

int sectorY (char* sectorstring) {
   /*returns the x coordinate of a specified sectorstring*/
   int t,begin,len;
   char* resultstring;

   if (sectorstring==NULL) return -1;
   resultstring=strdup(sectorstring);
   t=0;
   begin=-1;
   len=strlen(resultstring)+1;
   while (t<len){
      if (begin>-1) {
         if (resultstring[t]==':') {
            len=t;
	    resultstring[t]='\0';
         }
         resultstring[t-begin]=resultstring[t];
      } else if (resultstring[t]==',') {
         begin=t+1;
	 resultstring[t]='\0';
      }
      t++;
   }
   t=arglist_integer(resultstring);
   free(resultstring);
   return t;

}


void printerrorstring(char* title,char *errormessage) {

   if (errormessage!=NULL) fprintf(stderr,"%s: Error: %s!\n\n",title,errormessage);
   fprintf(stderr,"This Program will create an image containing\n   the average brightness values in all 10x10 Pixel sectors\n");
   fprintf(stderr,"The Sectorlist will go to stdout, the text to stderr.\n");
   fprintf(stderr,"For machine parsing try \"%s <arguments> 2>/dev/null | <parseprog>\"\n\n",title);
   fprintf(stderr,"Usage: %s [ -s <value> | --sensitivity=<value> ] \\\n",title);
   fprintf(stderr,"        [ --absolute ] \\\n");
   fprintf(stderr,"        [ --exclude [<x>,<y>] [<x>,<y>] ... [<x>,<y>] --end ] \\\n");
#ifdef USE_CLUSTER
   fprintf(stderr,"        [ -j <threads> ] \\\n");
#endif   
   fprintf(stderr,"        [ --sectorsize <value> ] <source> [<destination>] [--help] [-h]\n\n");
   fprintf(stderr,"    Absolute: Use this flag if you want motiontrack just to\n");
   fprintf(stderr,"              test if two images show the same motive\n");
   fprintf(stderr,"              instead of detecting moving objects.\n");
   fprintf(stderr," Sensitivity: 0 detect smallest motions, much false alarms.\n");
   fprintf(stderr,"              1 some lesser sensitivity, less flase alarms.\n");
   fprintf(stderr,"              ...\n");
   fprintf(stderr,"              9 detect almost no motion, no false alarms.\n");
   fprintf(stderr,"              default is \"-s 5\"\n");
   fprintf(stderr,"     Exclude: A list of sectors to ignore.\n");
   fprintf(stderr,"              can be given as [<x>,<y>:<b>] like in the output\n");
   fprintf(stderr,"              End the list with --end.\n");
   fprintf(stderr,"              default is none\n");
   fprintf(stderr,"  Sectorsize: The size of a sector, default is 5 (pixel)\n\n");
}

int main (int argc, char *argv[]) {
   ImagePtr imsource,imdest;	/*Working Images*/
   struct sectorlist* result;	/*List of Sectors*/
   int value;			/*Sensitivity*/
   char* valuechar;		/*Option string*/
   int answer;			/*return value*/
   int deltabright,t,sectorsize;/*check integers*/
   int method;			/*calculation method*/
   struct arglist* carglist;	/*commandline options*/
#ifdef USE_CLUSTER
   int threads;			/*number of threads*/
#endif

   carglist = arglist_new(argc, argv);
   arglist_addarg (carglist,"--help",0);
   arglist_addarg (carglist,"-h",0);
   arglist_addarg (carglist,"--absolute",0);
   arglist_addarg (carglist,"-s",1);
   arglist_addarg (carglist,"--sensitivity",1);
   arglist_addarg (carglist,"-s0",0);
   arglist_addarg (carglist,"-s1",0);
   arglist_addarg (carglist,"-s2",0);
   arglist_addarg (carglist,"-s3",0);
   arglist_addarg (carglist,"-s4",0);
   arglist_addarg (carglist,"-s5",0);
   arglist_addarg (carglist,"-s6",0);
   arglist_addarg (carglist,"-s7",0);
   arglist_addarg (carglist,"-s8",0);
   arglist_addarg (carglist,"-s9",0);
   arglist_addarg (carglist,"--sectorsize",1);
   arglist_addarg (carglist,"--end",0);
   arglist_addarg (carglist,"--exclude",10000);
   arglist_addarg (carglist,"-j",1);

   printwelcomestring();

   if ((arglist_arggiven(carglist,"--help")==0) || (arglist_arggiven(carglist,"-h")==0)) {
      printerrorstring(argv[0],NULL);
      printusagestring();
      return -1;
   }

   if ((arglist_parameter(carglist,"VOIDARGS",2)!=NULL) || (arglist_parameter(carglist,"VOIDARGS",0)==NULL)){
      printerrorstring(argv[0],"Error parsing commandline");
      printusagestring();
      return -1;
   }
   /*Check parameter count*/

#ifdef USE_CLUSTER
   threads=DEFAULT_THREADS;
   if (arglist_arggiven(carglist,"-j")==0) {
      threads=arglist_integer(arglist_parameter(carglist,"-j",0));
   }
   if (threads<1) {
      printerrorstring(argv[0],"Error parsing commandline,\nprocess amount <threads> has to be greater 0.");
      printusagestring();
      return -1;
   }
   /*Check process count */

   cluster_setpnum(threads);
#endif

   sectorsize=5;
   if (arglist_arggiven(carglist,"--sectorsize")==0) {
      sectorsize=arglist_integer(arglist_parameter(carglist,"--sectorsize",0));
   }
   if (sectorsize<=0) {
      printerrorstring(argv[0],"Error parsing commandline,\nsectorsize <value> has to be any positive integer");
      printusagestring();
      return -1;
   }
   /*Checked for Option sectorsize */

   if ((arglist_arggiven(carglist,"--sensitivity")==0) || (arglist_arggiven(carglist,"-s")==0)) {
      valuechar=arglist_parameter(carglist,"-s",0);
      if (valuechar==NULL) {
         valuechar=arglist_parameter(carglist,"--sensitivity",0);
      }
      if (arglist_isinteger(valuechar)!=0) {
         printerrorstring(argv[0],"Error parsing commandline,\nsensitivity <value> has to be between 0 and 9");
         printusagestring();
         return -1;
      }
      value=arglist_integer(valuechar);
   } else {
      value=5;
   }
   if (value>9) {
      printerrorstring(argv[0],"Error parsing commandline,\nnsensitivity <value> has to be between 0 and 9");
      printusagestring();
      return -1;
   }
   if (arglist_arggiven(carglist,"-s0")==0) value=0;
   if (arglist_arggiven(carglist,"-s1")==0) value=1;
   if (arglist_arggiven(carglist,"-s2")==0) value=2;
   if (arglist_arggiven(carglist,"-s3")==0) value=3;
   if (arglist_arggiven(carglist,"-s4")==0) value=4;
   if (arglist_arggiven(carglist,"-s5")==0) value=5;
   if (arglist_arggiven(carglist,"-s6")==0) value=6;
   if (arglist_arggiven(carglist,"-s7")==0) value=7;
   if (arglist_arggiven(carglist,"-s8")==0) value=8;
   if (arglist_arggiven(carglist,"-s9")==0) value=9;
   /*Checked for option sensitivity*/

   deltabright=25;
   /*default value for sensitivity*/
   if (value==0) deltabright=7;
   if (value==1) deltabright=9;
   if (value==2) deltabright=12;
   if (value==3) deltabright=16;
   if (value==4) deltabright=20;
   if (value==5) deltabright=25;
   if (value==6) deltabright=32;
   if (value==7) deltabright=40;
   if (value==8) deltabright=50;
   if (value==9) deltabright=64;


   imsource=loadim(arglist_parameter(carglist,"VOIDARGS",0));
   if (imsource==NULL) {
      printerrorstring(argv[0],"Error loading source image 1");
      printusagestring();
      return -1;
   }
   /*Load Sourcefile*/

   
   if (arglist_arggiven(carglist,"--absolute")==0) {
      method=1;
      deltabright*=3;
   } else {
      method=0;
   }
   result=checkmove(&imdest,imsource,deltabright,sectorsize,method);
   /*Do the main work in checkmove.h*/

   t=0;
   if (arglist_arggiven(carglist,"--exclude")==0) {
      if (arglist_arggiven(carglist,"--end")!=0) {
         printerrorstring(argv[0],"Exclude list has no --end ");
         printusagestring();
         return -1;
      }
      valuechar=arglist_parameter(carglist,"--exclude",t);
      while (valuechar!=NULL) {
         fprintf(stderr,"Excluding sector %i -- %s.\n",t,valuechar);
	 fprintf(stderr,"Xcoord = %i, Ycoord = %i\n",sectorX(valuechar),sectorY(valuechar));
         sectorlist_remsector(result,sectorX(valuechar),sectorY(valuechar));
         valuechar=arglist_parameter(carglist,"--exclude",++t);
      }
   }
   /*Exclude the specified exclusion sectors*/

   if (arglist_parameter(carglist,"VOIDARGS",1)!=NULL) {
      if (saveim(imdest,arglist_parameter(carglist,"VOIDARGS",1))!=0) {
         printerrorstring(argv[0],"Error saving destination image");
      }
      /*Save the resulting image*/
   }

   destroyim(imsource);
   destroyim(imdest);
   /*We free our memory*/


   answer=sectorlist_print(result);
   /*give back what we have*/

   sectorlist_kill(result);
   /*free the memory of our sectorlist manually*/

   arglist_kill(carglist);
   /*i forgot to kill the commandline argument list*/


   return answer;
}

