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

#include "boolean.h"
#include "file.h"
#include "xym.h"
#include "thdrad.h"
#include "wcs.h"
#include "verbose.h"

void usage(void);
void check_input(int argc, char *argv[], char *input, char *output, double *alpha, double *delta, double *edge);

int main(int argc, char *argv[]){
   int i, num, ndata;
   xym *data;
   char input[FILE_LENGTH], output[FILE_LENGTH];
   double edge, alpha_c, delta_c, alpha, delta, x, y, m;
#ifdef VERBOSE
   Boolean verb=TRUE;
#else
   Boolean verb=FALSE;
#endif
   FILE *flog, *fout;

   flog=stderr;
   check_input(argc,argv,input,output,&alpha_c,&delta_c,&edge);
   if(alpha<0) alpha+=360;
   alpha_c*=(M_PI/180); delta_c*=(M_PI/180);
   if(check_alpha_delta(alpha_c,delta_c)!=TRUE) exit(1);

   data=load_xym(input,&ndata);
   if(verb==TRUE) print_load_xym(flog,ndata,input);
   fout=fileopen(output,"w");
   for(i=0,num=0;i<ndata;i++){
      alpha=get_xym_x(data[i])*(M_PI/180);
      delta=get_xym_y(data[i])*(M_PI/180);
      calc_xy(alpha_c,delta_c,alpha,delta,&x,&y);
      x*=60; y*=60;
      if(fabs(x)>edge||fabs(y)>edge) continue;
      m=get_xym_m(data[i]);
      fprintf(fout,FORMAT_XYM_OUT,x,y,m);
      ++num;
   }
   if(verb==TRUE) print_nobject_output(flog,num,output);
   fclose(fout); fclose(flog);
   destroy_xym(ndata,data);
   return 0;
}

void usage(void){
   fprintf(stderr,"\nUsage -> get_local_coordinate  input  output  alpha  delta  edge\n");
   fprintf(stderr,"    input : x y m\n");
   fprintf(stderr,"    output : the name of output\n");
   fprintf(stderr,"    alpha delta (degree): the approximate coordinate of the image center\n");
   fprintf(stderr,"    edge (arcsec) : output inside [RA-edge:RA+edge][Dec-edge:Dec+edge]\n\n");
   exit(1);
}

void check_input(int argc, char *argv[], char *input, char *output, double *alpha, double *delta, double *edge){
   if(argc!=6) usage();
   strcpy(input,argv[1]);
   strcpy(output,argv[2]);
   *alpha=atof(argv[3]);
   *delta=atof(argv[4]);
   *edge=atof(argv[5]);
}
