#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include <fitsio.h>
#include "./qckisort.c"
#include "./getmedi2.c"

#ifdef _OPENMP
#include <omp.h>
#endif


/*
twflatlev.c
gcc -O2 -lm -o twflatlev twflatlev.c -lcfitsio
*/

int readfz(short data[], char *fname);

int main (int argc, char**argv)
{
    FILE    *fl,*fout;
    short   *data;
    int     *oclip;
    int     i,j,xynum=1048576;
    char    line[40],fname1[40],fname2[60];
    char    datedir[10];
    float   midpt,stdev;
    int     fzstat;
    int     ocnum;
    int     slen;
    char    suffix[4];
    char    **fits1arr,**fits2arr;
    int     ifnum,lnum,jj;


    if (argc < 3){
      fprintf(stderr, "usage : twflatlev date list\n");
      return 0;
    }
    sprintf(datedir,argv[1]);
    
    if(NULL==(fl=fopen(argv[2],"r"))){
	printf("\n [%s] can not be opened. \n",argv[2]);
	exit(1);
    }

    lnum=0;
    while(fgets(line, sizeof(line), fl) !=NULL){
      lnum++;
    }
    fclose(fl);

    fits1arr=(char**)malloc(lnum*sizeof(char)*60);
    fits2arr=(char**)malloc(lnum*sizeof(char)*60);
    ifnum=0;
    fout=fopen("twflat.tmp", "w");
    fl=fopen(argv[2],"r");
    while(fgets(line, sizeof(line), fl) !=NULL){
      sscanf(line, "%s\n", fname1);

      strcpy(fname2,"../");
      strcat(fname2,datedir);
      strcat(fname2,"/rawdata/");
      strcat(fname2,fname1);

      slen=strlen(fname1);
      slen=slen-3;
      memcpy(suffix,fname1+slen,3);  suffix[3]='\0';
      if(strcmp(suffix,".fz")==0 || strcmp(suffix,".ic")==0){
        strcat(fname2,"[1]");
      }

      fits1arr[ifnum]=(char*)malloc(60);
      fits2arr[ifnum]=(char*)malloc(60);
      strcpy(fits1arr[ifnum],fname1);
      strcpy(fits2arr[ifnum],fname2);

      ifnum++;
      strcpy(fname2,"");

    }
    fclose(fl);

#ifdef _OPENMP
#pragma omp parallel for private(data,fzstat,ocnum,i,oclip,j,midpt,stdev,k,cnum,clip)
#endif
    for(jj=0; jj<ifnum; jj++){

      data=(short*)malloc(xynum*sizeof(short));
      fzstat=readfz(data,fits2arr[jj]);
      if(fzstat==1){
	printf("fzstat==1\n");
      }

      ocnum=0;
      for(i=0; i<xynum; i++){
	if(i%4==0){
          ocnum++;
	}
      }
      oclip=(int*)malloc(ocnum*sizeof(int));  
      j=0;
      for(i=0; i<xynum; i++){
	if(i%4==0){
	  oclip[j]=data[i];
          j++;
	}
      }
      free(data);

      getmedi2(oclip,ocnum,&midpt,&stdev,0,20000);

      fprintf(fout,"%s %.1f\n", fits1arr[jj],midpt);
      free(oclip);

    }
    fclose(fout);

    return 0;
}


int readfz(short data[], char *fname)
{

  fitsfile  *fptr;         
  int       status = 0;  /* MUST initialize status */
  long      datanum=1024*1024;
  long      fpixel[2]={1,1};

  fits_open_file(&fptr, fname, READONLY, &status);
  fits_read_pix(fptr,TSHORT,fpixel,datanum,NULL,data,NULL,&status); 
  fits_close_file(fptr, &status);

  if (status)          /* print any error messages */
    fits_report_error(stderr, status);
  return(status);

}

