#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "./gethead.c"
#include "./swapfloat.c"
#include "./swapshort.c"

int main (int argc, char**argv)
{
 
  FILE   *fp;
  float  *data1;
  short  *data2;
  int    i, xynum=1048576;
  int    datanum = ((int)(xynum*sizeof(float)/2880)+1)*2880/sizeof(float);
  int    hfact, headsize;
  char   frame1[50], frame2[50];  /*  20 -> 50 */
  char   *header;
  int    mvalue;

  if (argc < 3){
    fprintf(stderr, "usage : domask target.fits mask.fits [m|p]\n");
    return 0;
  }

  sprintf(frame1, "%s", argv[1]);
  sprintf(frame2, "%s", argv[2]);
  if (strcmp(argv[3], "m") == 0){
    mvalue = -32000;
  } else if (strcmp(argv[3], "p") == 0){
    mvalue = 32000;
  } else {
    fprintf(stderr, "usage : domask target.fits mask.fits [m|p]\n");
    return 0;
  }

  hfact = gethead(frame1);
  if (hfact == 0){
    fprintf(stderr, "The header size was not obtained.\n");
    return 0;
  }
  headsize = hfact*2880;

  data1 = (float*)malloc(datanum*sizeof(float));
  header = (char*)malloc(headsize*sizeof(char));
  fp = fopen(frame1, "rb");
  fread(header, sizeof(char), headsize, fp);
  fread(data1, sizeof(float), datanum, fp);
  fclose(fp);

  for (i=0; i<datanum; i++){
    swapfloat(&data1[i]);
  }

  data2 = (short*)malloc(xynum*sizeof(short));
  fp = fopen(frame2, "rb");
  fseek(fp, 2880, SEEK_SET);
  fread(data2, sizeof(short), xynum, fp);
  fclose(fp);
  
  for (i=0; i<xynum; i++){
    swapshort(&data2[i]);
    if (data2[i] < 0){
      data1[i]= mvalue;
    }
  }

  for (i=0; i<datanum; i++){
    swapfloat(&data1[i]);
  }

  fp=fopen(frame1, "wb");
  fwrite(header, sizeof(char), headsize, fp);
  fwrite(data1, sizeof(float), datanum, fp);
  fclose(fp);

  free(data1);
  free(data2);
  free(header);

  return 0;


}
