#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <math.h>
#include <gsl/gsl_sort.h>
#include <gsl/gsl_statistics_double.h>

#include <sys/time.h>

#include "limits.h"
                    
int main (int argc, char **argv){
 DIR *dp;
 struct dirent *ep;

 FILE *lightcurvefile;
 FILE *outlightcurvefile;
 double jd,mag,merr,x,y,app;
 char string[FILENAME_LENGTH];

 double *mag_a = NULL;//malloc(MAX_NUMBER_OF_OBSERVATIONS*sizeof(double));
 mag_a=malloc(sizeof(double));
 double *merr_a = NULL;
 merr_a=malloc(sizeof(double));
 double mean_mag;
 double mag_sigma;
 int i;
 
 double min_flare_amplitude;
 double reference_mag,reference_merr;
 double mag_difference;
 
 char lightcurve_tmp_filename[FILENAME_LENGTH];

 if( argc>=2 && 0==strcmp("-h",argv[1]) ){
  fprintf(stderr,"Derect flares using out*dat files (assuming there were only three frrames - the reference and two new).\n");
  fprintf(stderr,"Usage:\n");
  fprintf(stderr,"%s [FLARE_MAG]\n",argv[0]);
  exit(0);
 }
 
 if( argc==2 ){
  min_flare_amplitude=atof(argv[1]);
 }
 else
  min_flare_amplitude=FLARE_MAG; /* Use default value from limits.h */
 
 dp = opendir ("./");
 if (dp != NULL){
  fprintf(stderr,"Detecting flares... ");
  while( ep = readdir(dp) )
   if( ep->d_name[0]=='o' && ep->d_name[1]=='u' && ep->d_name[2]=='t' && ep->d_name[strlen(ep->d_name)-1]=='t' && ep->d_name[strlen(ep->d_name)-2]=='a' && ep->d_name[strlen(ep->d_name)-3]=='d' ){
    lightcurvefile=fopen(ep->d_name,"r");
    if( NULL==lightcurvefile ){
     fprintf(stderr,"ERROR: Can't open file %s\n",ep->d_name);
     exit(1);
    }
    /* Compute median mag & sigma */
    fscanf(lightcurvefile,"%lf %lf %lf %lf %lf %lf %s",&jd,&reference_mag,&reference_merr,&x,&y,&app,string); // first line in the lightcurve file is the reference image
    i=0;
    while(-1<fscanf(lightcurvefile,"%lf %lf %lf %lf %lf %lf %s",&jd,&mag,&merr,&x,&y,&app,string)){
     mag_a[i]=mag;
     merr_a[i]=merr;
     i++;
     mag_a=realloc(mag_a,(i+1)*sizeof(double));
     merr_a=realloc(merr_a,(i+1)*sizeof(double));
    }
    fclose(lightcurvefile);
    if( i<HARD_MIN_NUMBER_OF_POINTS )continue; // we don't need lightcurves with small number of points.
    
    mean_mag=gsl_stats_min(mag_a,1,i);//gsl_stats_mean(mag_a,1,i);
    mag_sigma=gsl_stats_mean(merr_a,1,i);
    mag_difference=reference_mag-mean_mag;
//    fprintf(stderr,"mean_mag=%8.4lf mag_sigma=%.4lf  mag_difference=%8.4lf  min_flare_amplitude=%.4lf \n", mean_mag, mag_sigma, mag_difference, min_flare_amplitude);

    if( mag_difference>min_flare_amplitude && mag_difference>5.0*sqrt(reference_merr*reference_merr+mag_sigma*mag_sigma) && gsl_stats_max(mag_a,1,i)-gsl_stats_min(mag_a,1,i)<5.0*sqrt(reference_merr*reference_merr+mag_sigma*mag_sigma) ){
     strcpy(lightcurve_tmp_filename,"candidates-flares.lst");    
     outlightcurvefile=fopen(lightcurve_tmp_filename,"a");
     if( NULL==outlightcurvefile ){
      fprintf(stderr, "\nAn ERROR has occured while processing file %s  mean_mag=%lf mag_sigma=%lf\n",ep->d_name,mean_mag,mag_sigma);
      fprintf(stderr,"ERROR: Can't open file %s\n",lightcurve_tmp_filename);
      exit(1);
     }
//     fprintf(stderr,"!\n");
     fprintf(outlightcurvefile,"%s  %d\n",ep->d_name,i+1);
     fclose(outlightcurvefile);
    }
   }
  (void) closedir (dp);
  }
  else
   perror("Couldn't open the directory\n");

  free(mag_a);
  
  system("while read A B ;do echo -n \"$A    $B  \" ; tail -n1 $A |awk '{printf \"%s %8.3f %8.3f  \",$7,$4,$5}' ; head -n1 $A |awk '{printf \"%s %8.3f %8.3f\\n\",$7,$4,$5}' ;done < candidates-flares.lst >> candidates-transients.lst");

  fprintf(stderr,"done!  =)\n");                                         

  return 0;
}
