/**
 * \file ToFLevel2.h
 * \author Gianfranca DeRosa / Wolfgang Menn / Rita Carbone with E. M. supervision
 */

#ifndef ToFLevel2_h
#define ToFLevel2_h
//
#include <TObject.h>
#include <TArrayI.h>
#include <TArrayF.h>
#include <TClonesArray.h>

#include <math.h> // EMILIANO
#include <iostream> // from ToFLevel2.cpp
#include <fstream> // Emiliano
#include <sstream> // Emiliano 
#include <string> // Emiliano


#include <ToFStruct.h>

#include <TrkLevel2.h> // Emiliano
#include <TrigLevel2.h> // Emiliano 
#include <GLTables.h> // Emiliano
#include <OrbitalInfo.h> // Emiliano
#include <ToFCore.h> // Emiliano
#include <physics/tof/TofEvent.h>

//
// Declaration of the core fortran routines
//
#define tofl2com tofl2com_
extern "C" int tofl2com();
#define toftrk toftrk_
extern "C" int toftrk();
#define rdtofcal rdtofcal_
//extern "C" int rdtofcal(char [], int *);
extern "C" int rdtofcal(const char *, int *);

//
// class which contains track related variables
//
#define ZTOF11 53.74
#define ZTOF12 53.04
#define ZTOF21 23.94
#define ZTOF22 23.44
#define ZTOF31 -23.49
#define ZTOF32 -24.34


class ToFGeom : public TObject {

private:
  TArrayI  ePlane, eXY;

public:
  ToFGeom() {
    int plane[24] = { 
      0, 0, 0, 0, 0, 0, 0, 0,
      1, 1, 1, 1, 1, 1, 
      2, 2,             
      3, 3,             
      4, 4, 4,
      5, 5, 5
    };
    int plXY[6]= {  2,  1,  1,  2,  2,  1 }; // X==1, Y==2 */
    ePlane.Set(24,plane);
    eXY.Set(6,plXY);
  }

  int GetPad(   int idpmt)  { return (int)((idpmt+0.5)/2.); }
  int GetPlane( int idpmt)  { return ePlane[ GetPad(idpmt) ];  }
  int GetXY(    int idpmt)  { return eXY[ GetPlane(idpmt) ]; }

   ClassDef(ToFGeom,1);

};


/**
 * \brief  Class which contains the PMT data
 *
 * If there is a valid ADC or a TDC value (value<4095) for a PMT, both ADC and TDC data
 * are stored in the PMT class.
 * Look in the ToFLevel2Ex.cxx example in the repository how to read the PMT class. 
 */
class ToFPMT : public TObject {

 private:

 public:
    Int_t pmt_id;     ///<the identification number of the PMT from 0 to 47
    Float_t adc;      ///<raw ADC value for this PMT
    Float_t tdc;      ///<raw TDC value for this PMT
    Float_t tdc_tw;   ///<time-walk corrected TDC value for this PMT
    Float_t l0flag_adc; ///< warning flags from unpacking
    Float_t l0flag_tdc; ///< warning flags from unpacking
    //
    ToFPMT();
    ToFPMT(const ToFPMT&);
    //
    ToFPMT* GetToFPMT(){return this;};
    void Clear(Option_t *t="");

    ClassDef(ToFPMT,3);
};

/**
 * \brief  Class used to calibrate adc to dEdx for each PMT
 *
 * Class used to calibrate adc to dEdx for each PMT
 */
class ToFdEdx : public TObject {

 private:
    //
    ToFGeom  eGeom;  // ToF geometry
    //
    Float_t  adc_he;
    TArrayF *eDEDXpmt;  // 0-47  pmt dEdx
    // parameters:
    TArrayF PMTsat;  // 0-47  saturation parameters
    Float_t adc[48];
    //

    TArrayF parAtt[48];      // 48 x 6
    TArrayF parPos[48];      // 48 x 4
    TArrayF parDesatBB[48];  // 48 x 3
    TArrayF parBBneg[48];    // 48 x 3
    TArrayF  parBBpos;    // 48 x 1
 
    double f_adcPC( float x );
    double f_BB( TArrayF &p, float x );
    double f_BB5B( float x );
    double f_att( TArrayF &p, float x ) ;
    double f_att5B( float x );
    double f_desatBB( TArrayF &p, float x );  
    double f_desatBB5B( float x );
    double f_pos( TArrayF &p, float x );
    double f_pos5B( float x );
    float Get_adc_he( int id, float pl_x[6], float pl_y[6]);

    Bool_t conn[12]; 

    UInt_t ts[12];
    UInt_t te[12];    
   
    
 public:
    ToFdEdx();   // class constructor
    ~ToFdEdx();  // class distructor
    //
    void Clear(Option_t *option="");
    void Delete(Option_t *option="");

    void Init(pamela::tof::TofEvent *tofl0 );  // init parameters
    void Init(Int_t i, Int_t j, Float_t adce);
    void Define_PMTsat();

    void ReadParAtt(            const char *fname  );
    void ReadParPos(            const char *fname  );
    void ReadParBBneg(          const char *fname  );
    void ReadParBBpos(          const char *fname  );
    void ReadParDesatBB(        const char *fname  );

    void CheckConnectors(UInt_t atime, GL_PARAM *glparam, TSQLServer *dbc);

    void Process( UInt_t atime, Float_t betamean, Float_t *xtr_tof, Float_t *ytr_tof, Int_t exitat=-1); //
    void Print(Option_t *option="");

    //    Float_t GetdEdx_pmt(Int_t ipmt) { return (Float_t)eDEDXpmt[ipmt]; }  // 0-47 dEdx for each PMT for tracked events
    Float_t GetdEdx_pmt(Int_t ipmt) { return eDEDXpmt->At(ipmt); }  // 0-47 dEdx for each PMT for tracked events
    //
    ToFdEdx* GetToFdEdx(){return this;};
    ClassDef(ToFdEdx,3);
};


/**
 * \brief Class which contains the tracker related variables
 *
 * We can use the ToF standalone to find hitted paddles, calculate beta, etc..
 * These results are then stored with the "trkseqno" = -1.
 * If we use the track from the tracker, then the penetration points in the
 * scintillators are calculated, which defines the hitted paddles. For these paddles
 * we calculate then all the output.
 * Note: The artificial ADC values are stored as dEdx in the output, the dEdx will be
 * by definition = 1. However, the artificial TDC values are just used internally
 * and not stored in the output. But one can see in both cases which PMT has artificial
 * values using "adcflag" and "tdcflag".
 * Look in the ToFLevel2Ex.cxx example in the repository how to read the tracker related
 * variables. 
 */
class ToFTrkVar : public TObject {

 private:

 public:
  //
  Int_t trkseqno; ///< tracker sequ. number: -1=ToF standalone, 0=first Tracker track, ...
  //
  Int_t npmttdc;  ///<number of the TDC measurements used to evaluate beta
  TArrayI pmttdc;  ///<contains the ID (0..47) for the PMT used to evaluate beta
  TArrayI tdcflag; ///<flag for artificial TDC, "0" if normal TDC value

/**
 * \brief beta, 12 measurements for the 12  combinations, beta[13] is modified weighted mean
 *
 * The 12 measurements are S11-S31, S11-S32, S12-S31, S12-S32, and then analogue for
 * S2-S3 and S1-S2. 
 * The calculation of beta[13] is now modified:
 * We check the individual weights for artificial TDC values, then calculate
 * am mean beta for the first time. In a second step we loop again through
 * the single measurements, checking for the residual from the mean
 * The cut on the residual reject measurements > "x"-sigma. A chi2 value is
 * calculated, furthermore a "quality" value by adding the weights which
 * are finally used. If all measurements are taken, "quality" will be = 505.
 * A chi2 cut around 3-4 and a quality-cut > 400 is needed for clean beta
 * The Level2 beta[12] which is derived in the fortran routines uses: 10.,200.,20.
 * This is not a very high quality measurement. One can re-calculate a new beta[13]
 * using the L2-method "CalcBeta"
 */
  Float_t beta[13]; 
  //
  Int_t npmtadc;  ///<number of the ADC measurements used for dEdx evaluation
  TArrayI pmtadc; ///<contains the ID (0..47) for the PMT used to evaluate dEdx
  TArrayI adcflag; ///<flag for artificial ADCs, "0" if normal ADC value
  TArrayF dedx;    ///<energy loss for this PMT in mip
  //
  Float_t xtofpos[3];  ///<x-measurement using the TDC values and the calibration from S12, S21, S32
  Float_t ytofpos[3];  ///<x-measurement using the TDC values and the calibration from S11, S22, S31
  //
  Float_t xtr_tof[6];  ///<x-measurement in the ToF layers from tracker
  Float_t ytr_tof[6];  ///<x-measurement in the ToF layers from tracker
  //
  ToFTrkVar();
  ToFTrkVar(const ToFTrkVar&);

  ToFTrkVar* GetToFTrkVar(){return this;};
  void Clear(Option_t *t="");

  Float_t CalcBeta(Float_t resmax, Float_t qualitycut, Float_t chi2cut);  //  Elena 2015

  ClassDef(ToFTrkVar,2);
  //
};

/**
 * \brief  Class to describe ToF LEVEL2 data
 *
 */

class ToFLevel2 : public TObject {
 private:

 public:
  //
  TClonesArray *PMT; ///<class needed to store PMT hit informations
  TClonesArray *ToFTrk; ///<track related variable class
  Int_t tof_j_flag[6];  ///<number of hitted paddle(s) for each ToF layer: flag = flag + 2**(paddlenumber-1)
  //
  Int_t unpackError;///< zero if no errors
  Int_t unpackWarning;///< zero if no warnings | bitwise: ... 3 2 1 0 --> bit 0 = discharging flag on at least one PMT (adc OR tdc), bit 1 = there is at least one PMT off (no tdc nor adc) which is included in the patterntrig,  bit 2 = PMTs hit are not enough to match trigger configuration, bit 3 = pattern trig does not match trigger configuration
  Int_t default_calib; ///< one if the default calibration has been used to process the data, zero otherwise
  //
  Float_t GetdEdx(Int_t notrack, Int_t plane, Int_t adcfl); // gf Apr 07
  Float_t GetdEdx(ToFTrkVar *trk, Int_t plane, Int_t adcfl); // gf Apr 07

  Float_t CalcBeta(Int_t notrack, Float_t resmax, Float_t qualitycut, Float_t chi2cut);  //  wm feb 08

  //
//  Float_t CalcBeta(Int_t notrack, Float_t resmax, Float_t chi2cut, Float_t qualitycut);   // wm feb 08
  //
  // methods to make life simplier during the analysis, returns a pointer to the ToFTrkVar class containing track related variables
  //
  Int_t ntrk(){return ToFTrk->GetEntries();};
  Int_t npmt(){return PMT->GetEntries();};

  //
  void GetLevel2Struct(cToFLevel2 *) const;
  //
  ToFTrkVar *GetToFTrkVar(Int_t notrack);
  ToFTrkVar* GetToFStoredTrack(Int_t seqno);///< returns pointer to the track set related to the seqno number
  ToFPMT *GetToFPMT(Int_t nohit);
  static Int_t GetPMTid(Int_t gg, Int_t hh);
  static TString GetPMTName(Int_t ind);
  
  static Int_t GetPlaneIndex(Int_t pmt_id);
  void GetMatrix(Int_t notrack, Float_t adc[4][12], Float_t tdc[4][12]);
  static void GetPMTIndex(Int_t pmt_id, Int_t &gg, Int_t &hh);

  // gf Apr 07
  void GetdEdxPaddle(Int_t notrack, Int_t paddleid, Int_t adcfl, Float_t &PadEdx, Int_t &SatWarning); // gf Apr 07
  void GetdEdxPaddle(ToFTrkVar *trk, Int_t paddleid, Int_t adcfl, Float_t &PadEdx, Int_t &SatWarning); // gf Apr 07
  static TString GetPMTName(Int_t ind, Int_t &iplane, Int_t &ipaddle,Int_t &ipmt);
  Int_t GetPaddleIdOfTrack(Float_t xtr, Float_t ytr, Int_t plane); // gf Apr 07 //EMXX
  Int_t GetPaddleIdOfTrack(Float_t xtr, Float_t ytr, Int_t plane, Float_t margin); // wm jun 2008
  static void GetPMTPaddle(Int_t pmt_id, Int_t &plane, Int_t &paddle); // gf Apr 07
  void GetPaddlePMT(Int_t paddle, Int_t &pmtleft, Int_t &pmtright); // gf Apr 07
  void GetPaddleGeometry(Int_t plane, Int_t paddle, Float_t &xleft, Float_t &xright, Float_t &yleft, Float_t &yright); // gf Apr 07
  Int_t GetPaddleid(Int_t plane, Int_t paddle);
  void GetPaddlePlane(Int_t padid, Int_t &plane, Int_t &paddle);
  Int_t GetNPaddle(Int_t plane);
  //
  //
  //
  Int_t Process(TrkLevel2 *trk, TrigLevel2 *trg, GL_RUN *run, OrbitalInfo *orb, Bool_t force); // Emiliano

  //
  //
  bool bit(int decimal, char pos);
  bool checkPMT(TString givenpmt);
  bool checkPMTpatternPMThit(TrigLevel2 *trg, int &pmtpattern, int &pmtnosignal);
  bool checkPMTpmttrig(TrigLevel2 *trg);
  void printPMT();

  //
  // constructor
  //
  ToFLevel2();
  ~ToFLevel2(){Delete();}; //ELENA
  void Delete(Option_t *t=""); //ELENA
  void Set();//ELENA
  //
  //
  ToFLevel2*   GetToFLevel2(){return this;};

/**
 * Method to get the z-position of the 6 TOF layers from the plane ID
 * @param plane_id Plane ID (11 12 21 22 31 32)
 */
  Float_t      GetZTOF(Int_t plane_id){
      switch(plane_id){
      case 11: return ZTOF11;
      case 12: return ZTOF12;
      case 21: return ZTOF21;
      case 22: return ZTOF22;
      case 31: return ZTOF31;
      case 32: return ZTOF32;
      default: return 0.;
      };
  };

    //
    // Paddles position
    //
    /*
      S11 8 paddles  33.0 x 5.1 cm
      S12 6 paddles  40.8 x 5.5 cm
      S21 2 paddles  18.0 x 7.5 cm
      S22 2 paddles  15.0 x 9.0 cm
      S31 3 paddles  15.0 x 6.0 cm
      S32 3 paddles  18.0 x 5.0 cm
    */

    Int_t  GetToFPlaneID(Int_t ip);
    Int_t  GetToFPlaneIndex(Int_t plane_id);
    Bool_t HitPaddle(Int_t ,Int_t); // EMXX 
    Int_t  GetNHitPaddles(Int_t plane);
    Int_t  GetTrueNHitPaddles(Int_t plane);
    void Clear(Option_t *t="");

    //
    TClonesArray *GetTrackArray(){return ToFTrk;} ///< returns a pointer to the track related variables array
    TClonesArray** GetPointerToTrackArray(){return &ToFTrk;}///< returns pointer to pointer to the track array
    void SetTrackArray(TClonesArray *track);///<set pointer to the track array


    //
    ClassDef(ToFLevel2,7);
};

#endif

