#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>

#include "boolean.h"
#include "file.h"
#include "xym.h"
#include "verbose.h"
#include "verification.h"
#include "opm_param.h"
#include "matched.h"

void usage(void);
void check_input(int argc, char *argv[], char *input1, char *input2, char *output, double *xcen, double *ycen, double *halfsize, double *tol);

int main(int argc, char *argv[]){
   int ndata1, ndata2;
   FILE *flog;
   char input1[FILE_LENGTH], input2[FILE_LENGTH], output[FILE_LENGTH];
   char item[100];
   double xcen, ycen, halfsize, tol;
   double coef[6]={ 1, 0, 0, 0, 1, 0 };
   xym *data1, *data2;
   opm_param setting;
#ifdef VERBOSE
   Boolean verb=TRUE;
   flog=stderr;
#else
   Boolean verb=FALSE;
   flog=NULL;
#endif

   check_input(argc,argv,input1,input2,output,&xcen,&ycen,&halfsize,&tol);
   if(verb==TRUE&&flog!=NULL){
      fprintf(flog,"# opm_match started\n\n");
      fprintf(flog,"    xcen=%g  ycen=%g  halfsize=%g  tol=%g\n\n",xcen,ycen,halfsize,tol);
   }

   get_opm_param_default(&setting);
   sprintf(item,"%g",xcen);
   set_opm_param1(3,&setting,item);
   sprintf(item,"%g",ycen);
   set_opm_param1(4,&setting,item);
   sprintf(item,"%g",halfsize);
   set_opm_param1(5,&setting,item);
   sprintf(item,"%g",tol);
   set_opm_param1(12,&setting,item);
   strcpy(item,"0");
   set_opm_param1(13,&setting,item);
   strcpy(item,"0");
   set_opm_param1(14,&setting,item);

   data1=load_xym(input1,&ndata1);
   if(verb==TRUE) print_load_xym(flog,ndata1,input1);
   sort_xym_x(ndata1,data1);
   sort_xym_m(ndata1,data1);

   data2=load_xym(input2,&ndata2);
   if(verb==TRUE&&flog!=NULL) print_load_xym(flog,ndata2,input2);
   sort_xym_x(ndata2,data2);
   sort_xym_m(ndata2,data2);

   verification(NULL,ndata1,data1,ndata2,data2,coef,&setting);
   output_matched_result(flog,output,ndata1,data1,ndata2,data2,coef,&setting);
   //if(verb==TRUE&&flog!=NULL);
   destroy_xym(ndata1,data1); destroy_xym(ndata2,data2);
   return 0;
}

void usage(void){
   fprintf(stderr,"\nUsage -> opm  input1  input2  output  xcen  ycen  halfsize  tol\n");
   fprintf(stderr,"    input1+input2 : x y m\n");
   fprintf(stderr,"    output : the name of output (format: id1 x1 y1 m1 id2 x2 y2 m2)\n");
   exit(1);
}

void check_input(int argc, char *argv[], char *input1, char *input2, char *output, double *xcen, double *ycen, double *halfsize, double *tol){
   if(argc!=8) usage();
   strcpy(input1,argv[1]);
   strcpy(input2,argv[2]);
   strcpy(output,argv[3]);
   *xcen=atof(argv[4]);
   *ycen=atof(argv[5]);
   *halfsize=atof(argv[6]);
   *tol=atof(argv[7]);
}
