#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, char *RA, char *Dec, double *edge);

int main(int argc, char *argv[]){
   int num;
   FILE *fin, *fout, *flog;
   double edge, alpha_c, delta_c, alpha, delta, x, y, mag;
   char line[LINE_LENGTH], input[FILE_LENGTH], output[FILE_LENGTH];
   char RA[20], Dec[20];
#ifdef VERBOSE
   Boolean verb=TRUE;
#else
   Boolean verb=FALSE;
#endif

   flog=stderr;
   check_input(argc,argv,input,output,RA,Dec,&edge);
   alpha_delta(RA,Dec,&alpha_c,&delta_c);
   if(check_alpha_delta(alpha_c,delta_c)!=TRUE) exit(1);

   fin=fileopen(input,"r");
   fout=fileopen(output,"w");
   num=0;
   while(!feof(fin)){
      fgets(line,sizeof(line),fin);
      if(comment_line(line)==TRUE||feof(fin)) continue;
      if(sscanf(line,"%s %s %lf",RA,Dec,&mag)!=3) continue;
      alpha_delta(RA,Dec,&alpha,&delta);
      calc_xy(alpha_c,delta_c,alpha,delta,&x,&y);
      x*=60; y*=60;
      fprintf(fout,FORMAT_XYM_OUT,x,y,mag);
      ++num;
   }
   if(verb==TRUE) print_nobject_output(flog,num,output);
   fclose(fin); fclose(fout); fclose(flog);
   return 0;
}

void usage(void){
   fprintf(stderr,"\nUsage -> get_local_coordinate  input  output  RA  Dec  edge\n");
   fprintf(stderr,"    input : x y m\n");
   fprintf(stderr,"    output : the name of output\n");
   fprintf(stderr,"    RA Dec : hh:mm:ss.s +-dd:mm:ss.s\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, char *RA, char *Dec, double *edge){
   if(argc!=6) usage();
   strcpy(input,argv[1]);
   strcpy(output,argv[2]);
   strcpy(RA,argv[3]);
   strcpy(Dec,argv[4]);
   *edge=atof(argv[5]);
}
