/* definitions */
#define NbossMAX 400
/* type de recherche de bosse */
#define BOSSEN
/* define FILTMED */

#include "sopnamsp.h"
#include "machdefs.h"
#include <stdlib.h>
#include <math.h>
#include <stdio.h>
#include <string.h>

#include "nomfits.h"
#include "fsvcache.h"
#include "nbtri.h"
#include "nbrandom.h"
#include "nbmath.h"
#include "fmath.h"
#include "filtccd.h"
#include "hbook.h"
#include "fsvst.h"
#include "transfost.h"
#include "nbsread.h"
#include "nbgene.h"

#include "ntuple.h"

void FILL_USER(void);

float *TimeU[NCOULMX],*FluxU[NCOULMX],*eFluxU[NCOULMX]
     ,*FluxflU[NCOULMX],*eFluxflU[NCOULMX];
int_4 npt[NCOULMX];
int nslues,nsgood;

POutPersist *pos_ = NULL;
NTuple *ntbosse = NULL;

/*==========================================================================*/
void UINIT(void)
{
 pos_ = new POutPersist("nbsread_bosse.ppf");
}

/*===========================================================================*/
#define NXNT 48
void UINITCCD(void)
{
int_4 ic,n;
nslues = nsgood = 0;
for(ic=0;ic<NCOULMX;ic++) {
  n = ( nmesure[ic] > 0 ) ? nmesure[ic] : 1 ;
  TimeU[ic] = (float*) malloc((size_t) n*sizeof(float));
  FluxU[ic] = (float*) malloc((size_t) n*sizeof(float));
  eFluxU[ic] = (float*) malloc((size_t) n*sizeof(float));
  FluxflU[ic] = (float*) malloc((size_t) n*sizeof(float));
  eFluxflU[ic] = (float*) malloc((size_t) n*sizeof(float));
}

// Create NTuple
const char *nament[NXNT] = {
      "etr","etb","fr","fb",
      "dmin1","dmin2","dm21","dm22",
      "x1","y1","nptr","nptb",
      "mostr","mostb","sintr","sintb",
      "u0","t0","tau","a0",
      "nbosr","nbosb",
      "t1Pr","t2Pr","pkPr","nPr","i1Pr","i2Pr",
      "t1Pb","t2Pb","pkPb","nPb","i1Pb","i2Pb",
      "t1Sr","t2Sr","pkSr","nSr","i1Sr","i2Sr",
      "t1Sb","t2Sb","pkSb","nSb","i1Sb","i2Sb",
      "rec1","rec2"
};
if(ntbosse == NULL) delete ntbosse;
ntbosse = new NTuple(NXNT,nament);

}

/*=========================================================================*/
void UDATCLEAN(int coul)
/* pour tuer une photo selon des criteres utilisateur, mettre date a GRAND2 */
{
int_4 ic = coul-1;
if(nmes[ic]<=0) return;
for(int i=0;i<nmes[ic];i++) {
  if(date[ic][i]<0.)  date[ic][i] = GRAND2;
  if(timeu[ic][i].FgCalib<=0) date[ic][i] = GRAND2;
}
}

/*=========================================================================*/
void UEVT(void)
{
int_4 i,n,ic
     ,nbosse[NCOULMX],npoint[NCOULMX][NbossMAX],rc[NCOULMX]
     ,ideb[NCOULMX][NbossMAX],ifin[NCOULMX][NbossMAX]
     ,classB[NCOULMX][NbossMAX],I[NCOULMX],II[NCOULMX]
     ,I1[NCOULMX],I2[NCOULMX],II1[NCOULMX],II2[NCOULMX];
float xnt[NXNT],t1p[NCOULMX],t2p[NCOULMX],t1s[NCOULMX],t2s[NCOULMX]
     ,min,max,dt0,dt1,recouv1,recouv2;
float SigmaI[NCOULMX],Most[NCOULMX],/* Mean[NCOULMX], */Sigma[NCOULMX]
     ,chi2[NCOULMX][NbossMAX],Probchi2[NCOULMX][NbossMAX];
float *FlU[NCOULMX], *eFlU[NCOULMX];

nslues++;

/* association rouge-bleu existante et correcte */
if(iet[1] <= 0 ) return;
if(staru[0].XRef <= 0 ) return;
if(staru[0].NumEt <= 0 ) return;
if(staru[0].FluxRef<= 0.) return;
if(staru[0].XRef>0) if(staru[1].FluxRef<= 0.) return;
FILL_USER();
/* nombre de mesures suffisant */
if( npt[0]<3 || npt[1]<3 ) return;

if( iet[0]%50 == 0 )
  printf("UEVT: et=[%7d,%7d] pt nmesure=[%5d,%5d] npt=[%5d,%5d]\n"
        ,iet[0],iet[1],nmesure[0],nmesure[1],npt[0],npt[1]);

nsgood++;

/****************** Filtre Median *******************************/
for(ic=0;ic<NCOULMX;ic++) {
  n = npt[ic];
  rc[ic] = FiltMed(FluxU[ic],eFluxU[ic],FluxflU[ic],eFluxflU[ic],n);
}
if(rc[0]<0 && rc[1]<0) return;

/**************** Choix du tableau pour les bosses ***************/
#if defined(FILTMED)
for(ic=0;ic<NCOULMX;ic++) {FlU[ic] = FluxU[ic]; eFlU[ic] = eFluxU[ic];}
#else
for(ic=0;ic<NCOULMX;ic++) {FlU[ic] = FluxflU[ic]; eFlU[ic] = eFluxflU[ic];}
#endif

/*********************** Calcul du sigma interne *****************/
for(ic=0;ic<NCOULMX;ic++) {
  n = npt[ic];
  SigmaI[ic] = SigmaInt(TimeU[ic],FlU[ic],eFlU[ic],&n,4.);
}
if(SigmaI[0]<=0 && SigmaI[1]<=0) return;

/****************** Calcul de la base ***************************/

/*
for(ic=0;ic<NCOULMX;ic++) {
  n = npt[ic];
  rc[ic] = BaseLine(FlU[ic],eFlU[ic],&n,4.,SigmaI[ic],&Mean[ic],&Sigma[ic],&Most[ic]);
}
if(rc[0]<0 || rc[1]<0) return;
*/
/*
for(ic=0;ic<NCOULMX;ic++)
  rc[ic] = BaseLineP(FlU[ic],eFlU[ic],npt[ic],-5,&Most[ic]);
if(rc[0]<=0 || rc[1]<=0) return;
*/
for(ic=0;ic<NCOULMX;ic++)
  rc[ic] = BaseLineS(FlU[ic],eFlU[ic],npt[ic],-5,&Most[ic],&Sigma[ic]);
if(rc[0]<=0 || rc[1]<=0) return;
 
/****************** Recherche des bosses *****************************/

for(ic=0;ic<NCOULMX;ic++) {
  n = npt[ic];
#if defined(BOSSEN)
  nbosse[ic] = BosseN(FlU[ic],eFlU[ic],n,Most[ic],1.5,4,1.,4,
               &chi2[ic][0],&npoint[ic][0],&Probchi2[ic][0],&ideb[ic][0],&ifin[ic][0],
               &classB[ic][0],NbossMAX);  
#else
  nbosse[ic] = Bosse(FlU[ic],eFlU[ic],n,Most[ic],5,1.,3.,
               &chi2[ic][0],&npoint[ic][0],&Probchi2[ic][0],&ideb[ic][0],&ifin[ic][0],
               &classB[ic][0],NbossMAX);
#endif
  if(nbosse[ic]>0) {
    I[ic]= classB[ic][0];
    I1[ic]= ideb[ic][I[ic]];
    I2[ic]= ifin[ic][I[ic]];
    t1p[ic] = TimeU[ic][I1[ic]];
    t2p[ic] = TimeU[ic][I2[ic]];
    if(nbosse[ic]>1) {
      II[ic]= classB[ic][1];
      II1[ic]= ideb[ic][II[ic]];
      II2[ic]= ifin[ic][II[ic]];
      t1s[ic] = TimeU[ic][II1[ic]];
      t2s[ic] = TimeU[ic][II2[ic]];
    }
  }
}

/********************** calcul du recouvrement R/B ************************/

recouv1 = -1.;
if (nbosse[0]>0 && nbosse[1]>0) {
  dt0 = t2p[0] - t1p[1];
  dt1 = t2p[1] - t1p[0];
  if ((t2p[0]-t1p[0]) < (t2p[1]-t1p[1])) {
    min = (t2p[0]-t1p[0]);
    max = (t2p[1]-t1p[1]);
  } else {
    min = (t2p[1]-t1p[1]);
    max = (t2p[0]-t1p[0]);
  }
  if ( dt0*dt1 < 0.) recouv1 = 0.;
  else if ((min<dt0) && (min<dt1)) recouv1 = min/max;
  else recouv1 = (dt0>dt1) ? dt1/dt0 : dt0/dt1;
}

recouv2 = -1.;
if (nbosse[0]>1 && nbosse[1]>1) {
  dt0 = t2s[0] - t1s[1];
  dt1 = t2s[1] - t1s[0];
  if ((t2s[0]-t1s[0]) < (t2s[1]-t1s[1])) {
    min = (t2s[0]-t1s[0]);
    max = (t2s[1]-t1s[1]);
  } else {
    min = (t2s[1]-t1s[1]);
    max = (t2s[0]-t1s[0]);
  }
  if ( dt0*dt1 < 0.) recouv2 = 0.;
  else if ((min<dt0) && (min<dt1)) recouv2 = min/max;
  else recouv2 = (dt0>dt1) ? dt1/dt0 : dt0/dt1;
}

/********************** on remplit le ntuple de selection **********************/

for(i=0;i<NXNT;i++) xnt[i] = -1.;
xnt[0]=  iet[0];                         /* etr */
xnt[1]=  iet[1];                         /* etb */
xnt[2] = staru[0].FluxRef;               /* fr */
xnt[3] = staru[1].FluxRef;               /* fb */
xnt[4] = staru[0].DisMin;                /* dmin1 */
xnt[5] = staru[1].DisMin;                /* dmin2 */
xnt[6] = staru[0].DisM2;                 /* dm21 */
xnt[7] = staru[1].DisM2;                 /* dm22 */
xnt[8] = staru[0].XPos;                  /* x1 */
xnt[9] = staru[0].YPos;                  /* y1 */
xnt[10] = npt[0];                        /* nptr */
xnt[11] = npt[1];                        /* nptb */

xnt[12] = Most[0];                       /* mostr */
xnt[13] = Most[1];                       /* mostb */
xnt[14] = SigmaI[0];                     /* sintr */
xnt[15] = SigmaI[1];                     /* sintb */

xnt[16] = mc.U0Sim;                      /* u0 */
xnt[17] = mc.T0Sim;                      /* t0 */
xnt[18] = mc.TauSim;                     /* tau */
xnt[19] = mc.A0Max;                      /* a0 */

xnt[20] = nbosse[0];                     /* nbosr */
xnt[21] = nbosse[1];                     /* nbosb */

/* bosse rouge 1ere */
if(nbosse[0]>0) {
  xnt[22] = t1p[0];                      /* t1Pr */
  xnt[23] = t2p[0];                      /* t2Pr */
  xnt[24] = Probchi2[0][I[0]];           /* pkPr */
  xnt[25] = npoint[0][I[0]];             /* nPr */
  xnt[26] = I1[0];                       /* i1Pr */
  xnt[27] = I2[0];                       /* i2Pr */
}

/* bosse bleue 1ere */
if(nbosse[1]>0) {
  xnt[28] = t1p[1];                      /* t1Pb */
  xnt[29] = t2p[1];                      /* t2Pb */
  xnt[30] = Probchi2[1][I[1]];           /* pkPb */
  xnt[31] = npoint[1][I[1]];             /* nPb */
  xnt[32] = I1[1];                       /* i1Pb */
  xnt[33] = I2[1];                       /* i2Pb */
}

/* bosse rouge 2sd */
if(nbosse[0]>1) {
  xnt[34] = t1s[0];                      /* t1Sr */
  xnt[35] = t2s[0];                      /* t2Sr */
  xnt[36] = Probchi2[0][II[0]];          /* pkSr */
  xnt[37] = npoint[0][II[0]];            /* nSr */
  xnt[38] = II1[0];                      /* i1Sr */
  xnt[39] = II2[0];                      /* i2Sr */
}

/* bosse bleue 2sd */
if(nbosse[1]>1) {
  xnt[40] = t1s[1];                      /* t1Sb */
  xnt[41] = t2s[1];                      /* t2Sb */
  xnt[42] = Probchi2[1][II[1]];          /* pkSb */
  xnt[43] = npoint[1][II[1]];            /* nSb */
  xnt[44] = II1[1];                      /* i1Sb */
  xnt[45] = II2[1];                      /* i2Sb */
}

/* recouvrement 1ere 2sd */
xnt[46] = recouv1;                       /* rec1 */
xnt[47] = recouv2;                       /* rec2 */

 ntbosse->Fill(xnt);

}

/*=========================================================================*/
void UENDCCD(void)
{
int ic;
printf("Nombre d etoiles lues= %d, bonnes= %d, mauvaises=%d\n"
      ,nslues,nsgood,nslues-nsgood);
fflush(stdout);
for(ic=0;ic<NCOULMX;ic++) {
  free(TimeU[ic]);
  free(FluxU[ic]);
  free(eFluxU[ic]);
  free(FluxflU[ic]);
  free(eFluxflU[ic]);
}

if(ntbosse->NEntry()>0) pos_->PutObject(*ntbosse,"ntbosse");
if(ntbosse!=NULL) delete ntbosse; ntbosse = NULL;
}

/*=========================================================================*/
void UEND(void)
{
 if(pos_!=NULL) delete pos_; pos_ = NULL;
}

/*=========================================================================*/
void FILL_USER(void)
{
int ic,i,j;
double Flux,FluxB,Xi2,ErrFlux;
  
for(ic=0;ic<NCOULMX;ic++) {
  npt[ic]=0;
  for(i=0;i<nmesure[ic];i++) {
    j = indexu[ic][i];
    FluxB = mesu[ic][j].FluxB;
    Flux = mesu[ic][j].Flux;
    ErrFlux = mesu[ic][j].ErrFlux;
    Xi2 = mesu[ic][j].Xi2;
    if( ErrFlux<0 ) ErrFlux *= -1.;
    if(Xi2<=0.)   continue;
    TimeU[ic][npt[ic]] = date[ic][j];
    if(mc.montecar > 0) Flux *= ampli[ic][j];
    FluxU[ic][npt[ic]] = Flux;
    eFluxU[ic][npt[ic]] = ErrFlux;
    npt[ic]++;
  }
}

}
