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

#include "boolean.h"
#include "file.h"
#include "matched.h"
#include "thdrad.h"

void usage(void);
Boolean check_input(int argc, char *argv[], char *input, double *crval);
void coef_sec2deg(double *coef);
void calc_cd_crpix(double *coef,double *cd,double *crpix);
void print_wcs_header(FILE *fp, double *cd,double *crpix,double *crval);

int main(int argc, char *argv[]){
   double cd[4], crpix[2], crval[2], coef[6];
   char input[FILE_LENGTH];
   if(check_input(argc,argv,input,crval)!=TRUE) usage();
   if(read_matched_coef(input,coef)!=TRUE){
      fprintf(stderr,"Failed to load transformation coefficients from %s\n",input); exit(1);
   }
   coef_sec2deg(coef);
   calc_cd_crpix(coef,cd,crpix);
   print_wcs_header(stdout,cd,crpix,crval);
   return 0;
}

void usage(void){
   fprintf(stderr,"Usage -> make_wcs_header  matched_file  RA  Dec\n");
   fprintf(stderr,"   matched_file : the name of output file of OPM\n");
   fprintf(stderr,"   RA/Dec : the reference equatorial coordinate\n");
   exit(1);
}

Boolean check_input(int argc, char *argv[], char *input, double *crval){
   double alpha, delta;
   if(argc!=4) return FALSE;
   strcpy(input,argv[1]);
   if(file_exist(input)!=TRUE) return FALSE;
   if(strstr(argv[2],":")!=NULL){
      alpha_delta(argv[2],argv[3],&alpha,&delta);
      crval[0]=alpha*(180/M_PI);
      crval[1]=delta*(180/M_PI);
   } else {
      crval[0]=atof(argv[2]);
      crval[1]=atof(argv[3]);
   }
   if(crval[0]<-180||crval[0]>360||crval[1]<-90||crval[1]>90){
      fprintf(stderr,"RA and Dec is out of range! (crval[0]=%.1f crval[1]=%.1f)\n",crval[0],crval[1]);
      return FALSE;
   }
   return TRUE;
}

void coef_sec2deg(double *coef){
   int i;
   for(i=0;i<6;i++) coef[i]/=(60.0*60.0);
}

void calc_cd_crpix(double *coef,double *cd,double *crpix){
   cd[0]=coef[0];
   cd[1]=coef[1];
   cd[2]=coef[3];
   cd[3]=coef[4];
   crpix[0]=(coef[1]*coef[5]-coef[2]*coef[4])/(coef[0]*coef[4]-coef[1]*coef[3]);
   crpix[1]=(coef[0]*coef[5]-coef[2]*coef[3])/(coef[1]*coef[3]-coef[0]*coef[4]);
}

void print_wcs_header(FILE *fp, double *cd,double *crpix,double *crval){
   fprintf(fp,"WCSAXES  2\n");
   fprintf(fp,"CTYPE1   'RA---TAN'\n");
   fprintf(fp,"CTYPE2   'DEC--TAN'\n");
   fprintf(fp,"CRPIX1   %-14.7f\n",crpix[0]);
   fprintf(fp,"CRPIX2   %-14.7f\n",crpix[1]);
   fprintf(fp,"CD1_1    %-14.7e\n",cd[0]);
   fprintf(fp,"CD1_2    %-14.7e\n",cd[1]);
   fprintf(fp,"CD2_1    %-14.7e\n",cd[2]);
   fprintf(fp,"CD2_2    %-14.7e\n",cd[3]);
   fprintf(fp,"LONPOLE  180\n");
   fprintf(fp,"CRVAL1   %-14.7f\n",crval[0]);
   fprintf(fp,"CRVAL2   %-14.7f\n",crval[1]);
   fprintf(fp,"CUNIT1   'deg     '\n");
   fprintf(fp,"CUNIT2   'deg     '\n");
}

