

/**
 * \file PamLevel2.h
 * \author Elena Vannuccini
 */
#ifndef pamlevel2_h
#define pamlevel2_h

#include <TRefArray.h>

#include <TrkStruct.h>
#include <TrkParams.h>
#include <TrkLevel0.h>
#include <TrkLevel1.h>
#include <TrkLevel2.h>
#include <TrkHough.h>
#include <CaloLevel0.h>
#include <CaloLevel1.h>
#include <CaloLevel2.h>
#include <ToFLevel2.h>
#include <TrigLevel2.h>
#include <S4Level2.h>
#include <NDLevel2.h>
#include <AcLevel2.h>
#include <OrbitalInfo.h>
#include <InclinationInfo.h> // EMILIANO, now this library is included in libDarthVader.so
			 // and the header installed in $PAM_INC. If you get the
			 // error "Cannot find InclinationInfo.h" update your DV installation
#include <OrientationInfo.h> // EMILIANO, now this library is included in libDarthVader.so
			 // and the header installed in $PAM_INC. If you get the
			 // error "Cannot find InclinationInfo.h" update your DV installation
#include <RunInfo.h>
#include <GLTables.h>


#include <TTree.h>
#include <TFriendElement.h>
#include <TChain.h>
#include <TChainElement.h>
#include <TFile.h>
#include <TList.h>
#include <TKey.h>
#include <TSystemFile.h>
#include <TSystemDirectory.h>
#include <TSQLServer.h>

#include <stdlib.h>
#include <iostream>
#include <iomanip>
using namespace std;

#define NCLONES 10

using namespace std;


/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
/**
 * \brief Class to describe GP output (to be moved to PamelaDigitizer)
 *
 */

class GPamela : public TObject {

 private:

 public:

    // Declaration of leave types
    Int_t           Irun;
    Int_t           Ievnt;
    Int_t           Ipa;
    Float_t         X0;
    Float_t         Y0;
    Float_t         Z0;
    Float_t         Theta;
    Float_t         Phi;
    Float_t         P0;
    Int_t           Nthtof;
    UChar_t         Ipltof[100];   //[Nthtof]
    UChar_t         Ipaddle[100];   //[Nthtof]
    UChar_t         Ipartof[100];   //[Nthtof]
    Float_t         Xintof[100];   //[Nthtof]
    Float_t         Yintof[100];   //[Nthtof]
    Float_t         Zintof[100];   //[Nthtof]
    Float_t         Xouttof[100];   //[Nthtof]
    Float_t         Youttof[100];   //[Nthtof]
    Float_t         Zouttof[100];   //[Nthtof]
    Float_t         Ereltof[100];   //[Nthtof]
    Float_t         Timetof[100];   //[Nthtof]
    Float_t         Pathtof[100];   //[Nthtof]
    Float_t         P0tof[100];   //[Nthtof]
    Int_t           Nthcat;
    UChar_t         Iparcat[50];   //[Nthcat]
    UChar_t         Icat[50];   //[Nthcat]
    Float_t         Xincat[50];   //[Nthcat]
    Float_t         Yincat[50];   //[Nthcat]
    Float_t         Zincat[50];   //[Nthcat]
    Float_t         Xoutcat[50];   //[Nthcat]
    Float_t         Youtcat[50];   //[Nthcat]
    Float_t         Zoutcat[50];   //[Nthcat]
    Float_t         Erelcat[50];   //[Nthcat]
    Float_t         Timecat[50];   //[Nthcat]
    Float_t         Pathcat[50];   //[Nthcat]
    Float_t         P0cat[50];   //[Nthcat]
    Int_t           Nthcas;
    UChar_t         Iparcas[50];   //[Nthcas]
    UChar_t         Icas[50];   //[Nthcas]
    Float_t         Xincas[50];   //[Nthcas]
    Float_t         Yincas[50];   //[Nthcas]
    Float_t         Zincas[50];   //[Nthcas]
    Float_t         Xoutcas[50];   //[Nthcas]
    Float_t         Youtcas[50];   //[Nthcas]
    Float_t         Zoutcas[50];   //[Nthcas]
    Float_t         Erelcas[50];   //[Nthcas]
    Float_t         Timecas[50];   //[Nthcas]
    Float_t         Pathcas[50];   //[Nthcas]
    Float_t         P0cas[50];   //[Nthcas]
    Int_t           Nthspe;
    UChar_t         Iparspe[100];   //[Nthspe]
    UChar_t         Itrpb[100];   //[Nthspe]
    UChar_t         Itrsl[100];   //[Nthspe]
    UChar_t         Itspa[100];   //[Nthspe]
    Float_t         Xinspe[100];   //[Nthspe]
    Float_t         Yinspe[100];   //[Nthspe]
    Float_t         Zinspe[100];   //[Nthspe]
    Float_t         Xoutspe[100];   //[Nthspe]
    Float_t         Youtspe[100];   //[Nthspe]
    Float_t         Zoutspe[100];   //[Nthspe]
    Float_t         Xavspe[100];   //[Nthspe]
    Float_t         Yavspe[100];   //[Nthspe]
    Float_t         Zavspe[100];   //[Nthspe]
    Float_t         Erelspe[100];   //[Nthspe]
    Float_t         Pathspe[100];   //[Nthspe]
    Float_t         P0spe[100];   //[Nthspe]
    UChar_t         Nxmult[100];   //[Nthspe]
    UChar_t         Nymult[100];   //[Nthspe]
    Int_t           Nstrpx;
    UChar_t         Npstripx[1000];   //[Nstrpx]
    UChar_t         Ntstripx[1000];   //[Nstrpx]
    UShort_t        Istripx[1000];   //[Nstrpx]
    //UInt_t        Istripx[1000];   //[Nstrpx]
    Float_t         Qstripx[1000];   //[Nstrpx]
    Float_t         Xstripx[1000];   //[Nstrpx]
    Int_t           Nstrpy;
    UChar_t         Npstripy[1000];   //[Nstrpy]
    UChar_t         Ntstripy[1000];   //[Nstrpy]
    UShort_t        Istripy[1000];   //[Nstrpy]
    //UInt_t        Istripy[1000];   //[Nstrpy]
    Float_t         Qstripy[1000];   //[Nstrpy]
    Float_t         Ystripy[1000];   //[Nstrpy]
    Int_t           Nthcali;
    UChar_t         Icaplane[4224];   //[Nthcali]
    UChar_t         Icastrip[4224];   //[Nthcali]
    Int_t           Icamod[4224];   //[Nthcali]
    Float_t         Enestrip[4224];   //[Nthcali]
    Int_t           Nthcal;
    UChar_t         Icapl[1000];   //[Nthcal]
    UChar_t         Icasi[1000];   //[Nthcal]
    UChar_t         Icast[1000];   //[Nthcal]
    Float_t         Xincal[1000];   //[Nthcal]
    Float_t         Yincal[1000];   //[Nthcal]
    Float_t         Zincal[1000];   //[Nthcal]
    Float_t         Erelcal[1000];   //[Nthcal]
    Int_t           Nthnd;
    UChar_t         Itubend[200];   //[Nthnd]
    UChar_t         Iparnd[200];   //[Nthnd]
    Float_t         Xinnd[200];   //[Nthnd]
    Float_t         Yinnd[200];   //[Nthnd]
    Float_t         Zinnd[200];   //[Nthnd]
    Float_t         Xoutnd[200];   //[Nthnd]
    Float_t         Youtnd[200];   //[Nthnd]
    Float_t         Zoutnd[200];   //[Nthnd]
    Float_t         Erelnd[200];   //[Nthnd]
    Float_t         Timend[200];   //[Nthnd]
    Float_t         Pathnd[200];   //[Nthnd]
    Float_t         P0nd[200];   //[Nthnd]
    Int_t           Nthcard;
    UChar_t         Iparcard[100];   //[Nthcard]
    UChar_t         Icard[100];   //[Nthcard]
    Float_t         Xincard[100];   //[Nthcard]
    Float_t         Yincard[100];   //[Nthcard]
    Float_t         Zincard[100];   //[Nthcard]
    Float_t         Xoutcard[100];   //[Nthcard]
    Float_t         Youtcard[100];   //[Nthcard]
    Float_t         Zoutcard[100];   //[Nthcard]
    Float_t         Erelcard[100];   //[Nthcard]
    Float_t         Timecard[100];   //[Nthcard]
    Float_t         Pathcard[100];   //[Nthcard]
    Float_t         P0card[100];   //[Nthcard]

    GPamela(){ Clear(); };
//    ~GPamela(){ Delete(); };
    ~GPamela(){ Clear(); };

    void Clear();
    void Delete();
    void SetBranchAddress( TChain* );
    void SetBranchAddress( TTree* t){ SetBranchAddress( (TChain*)t );};

    GPamela*    GetGPamela(){return this;};

    ClassDef(GPamela,1);

};
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////



/**
 * \brief Class to describe particle tracks in the apparatus, including tracker and track-related variables from other detectors (calorimeter and TOF).
 *
 * This class inherites from TrkTrack, CaloTrkVar ecc...
 *
 */
//class PamTrack : public TrkTrack, public CaloTrkVar, public ToFTrkVar {
class PamTrack : public TObject {

 private:

    TrkTrack*   trk_track;
    CaloTrkVar* calo_track;
    ToFTrkVar*  tof_track;
    OrbitalInfoTrkVar*  orb_track;
    Int_t pscore;
    Int_t iscore;
    bool candeleteobj;

//    TClonesArray *Cluster;        ///< clusters (if stored)

 public:

    PamTrack();
    PamTrack(TrkTrack* , CaloTrkVar* , ToFTrkVar*, OrbitalInfoTrkVar* );
    PamTrack(const PamTrack&);
    ~PamTrack(){ Delete(); };

    void Clear();
    void Clear(Option_t *option){Clear();};
    void Delete();

    Bool_t IsSolved(){if ((pscore-iscore)>0) return true; return false;};
    Int_t GetScore(){return (pscore-iscore);};
    Int_t GetPScore(){return (pscore);};
    Int_t GetIScore(){return (iscore);};
    void SetPScore(Int_t p){pscore=p;};
    void SetIScore(Int_t i){iscore=i;};

    TrkTrack*   GetTrkTrack(){return trk_track;};
    CaloTrkVar* GetCaloTrack(){return calo_track;};
    ToFTrkVar*  GetToFTrack(){return tof_track;};
    OrbitalInfoTrkVar*  GetOrbitalInfoTrack(){return orb_track;};

    ClassDef(PamTrack,2);
};

/**
 * \brief Class to describe PAMELA LEVEL2 data.
 *
 * This class inherites from TrkLevel2, CaloLevel2 ecc... and it overrides the TrkLevel2:GetTrack(int it) and TrkLevel2:GetTrackImage(int it) methods.
 * This allows to solve the tracker ambiguity (that is, to choose between track images) by using also information from other detectors.
 */

//class PamLevel2 : public CaloLevel2, public CaloLevel1, public ToFLevel2, public TrkLevel2, public TrkLevel1, public TrkHough, public TrigLevel2, public S4Level2, public NDLevel2, public AcLevel2, public OrbitalInfo {
class PamLevel2 : public TObject {

 private:

    // ------------------------------
    // variables to retrieve run info
    // ------------------------------
    Long64_t  irun;          //current run entry, relative to the TChain
    Long64_t  irunt;         //current run entry, relative to the TTree in the TChain
    Long64_t  runfirstentry; //first entry of run, relative to the TChain
    Long64_t  runlastentry;  //last  entry of run, relative to the TChain
    Long64_t  irunentry;     //position of current entry, relative to the run
    TChain*   run_tree;
    TTree*    run_tree_clone;
    TChain*   sel_tree;
    TTree*    sel_tree_clone;
    int *irunoffset;
    GL_TIMESYNC *gltsync; // Emiliano

    // -------------------------------------------
    // variables to store total live and dead time
    // -------------------------------------------
    ULong64_t  totdltime[3];// 0=live 1=dead 2=n.events

    // ---------------------------------
    // variables to retrieve level0 info
    // ---------------------------------
    TFile*      l0_file;
    TTree*      l0_tree;
    Int_t       iroot;
    Int_t       prevshift; // to remember if any shift is needed to synchronize l0 and l2 data instead of calculating any time
    Int_t       maxshift; // EMILIANO maximum discrepancy between L2 and L0 data (the bigger the better concering synch but the processing speed drops) default = 10
    // --------------------------------------------
    // variables to store Level0 info (if required)
    // --------------------------------------------
    EventHeader* h0_obj;
    TrkLevel0*   trk0_obj;
    CaloLevel0*  calo0_obj;

    // ---------------------------
    // variables to connect the DB
    // ---------------------------
    TSQLServer* dbc;
    TString host;
    TString user;
    TString psw;

    // ---------------------------------------------
    // variables to retrieve and clone level1-2 info
    // ---------------------------------------------
    TChain* pam_tree;
    TTree*  pam_tree_clone[NCLONES];

    // --------------------------------------------
    // variables to store Level1-2 info
    // --------------------------------------------
    TrkLevel1*   trk1_obj;
    TrkLevel2*   trk2_obj;
    TrkHough*    trkh_obj;
    CaloLevel1*  calo1_obj;
    CaloLevel2*  calo2_obj;
    ToFLevel2*   tof_obj;
    TrigLevel2*  trig_obj;
    S4Level2*    s4_obj;
    NDLevel2*    nd_obj;
    AcLevel2*    ac_obj;
    OrbitalInfo* orb_obj;
    GL_RUN*      run_obj;
    SoftInfo*    soft_obj; // Emiliano

    // --------------------------------------------
    // variables to handle GP
    // --------------------------------------------
    GPamela*     gp_obj;

    // -----------------------------------
    // variables to sort the track
    // -----------------------------------
    TClonesArray *tsorted;
    TClonesArray *timage;
    PamTrack    *track; //store the last required
    TString howtosort;
    Float_t sortthr;

    Bool_t issorted;     // true if the current event has already been sorted with the current sort criteria
    Long64_t lastsorted; // the last event whose tracks has been sorted
    // --------------------------------------
    // flags to load level0-1-2 trees/braches
    // --------------------------------------
    Bool_t CAL2; //level2 branch
    Bool_t CAL1; //level1 branch
    Bool_t CAL0; //yoda

    Bool_t TRK2; //level2 branch
    Bool_t TRK1; //level1 branch
    Bool_t TRKh; //hough branch
    Bool_t TRK0; //yoda

    Bool_t TOF;
    Bool_t TOF0;

    Bool_t TRG;
    Bool_t S4;
    Bool_t ND;
    Bool_t AC;
    Bool_t ORB;

    Bool_t GP; //GP simulation tree

    // -----------
    // other flags
    // -----------
    Bool_t RUN;   // RunInfo tree
    Bool_t ISGP;  // GP simulation (...sort of patch, to skip OBT check, since OrbitalInfo is sometime missing)
    Int_t  SELLI; // tree of selected events (there is a selection list)

    Bool_t DBG;

    void Initialize();


 public:

    PamLevel2(TString ddir,TList *list,TString detlist);
    PamLevel2(TString ddir,TString list,TString detlist);
    PamLevel2(TString ddir,TString list);
    PamLevel2();
    ~PamLevel2(){Delete();};

    void Clear();
    void Reset();
    void Delete();


//  =============================================
//  methods needed to read/write Level0-1-2 trees
//  =============================================
    void    SetWhichTrees(TString);
    void    GetWhichTrees(TFile*);

    TTree*  GetPamTree(TFile*,TString);
    TTree*  GetPamTree(TFile* f){return GetPamTree(f,"");};

    TList*  GetListOfLevel2Files(TString, TString);
    Bool_t  CheckLevel2File(TString);
    TChain* GetPamTree(TList*,TString);
    TChain* GetPamTree(TString ddir,TString list,TString detlist){ return GetPamTree(GetListOfLevel2Files(ddir,list),detlist); };
    TChain* GetPamTree(TString ddir,TString list){ return GetPamTree(GetListOfLevel2Files(ddir,list),""); };
    TChain* AddFriend(TString);

    TTree*  GetRunTree(TFile*);
    TChain* GetRunTree(TList*);
    TChain* GetRunTree(TString ddir,TString list){ return GetRunTree(GetListOfLevel2Files(ddir,list)); };
    Bool_t  UpdateRunInfo(Long64_t);//{ return UpdateRunInfo(run_tree,iev); };
    Bool_t  UpdateRunInfo(TTree *,Long64_t);
    Bool_t  UpdateRunInfo(TChain *,Long64_t);

    void    CreateCloneTrees0(TChain *fChain, TFile* file);
    void    CreateCloneTrees(TFile* file);
    void    CreateCloneTrees(){CreateCloneTrees(NULL);};
    void    FillCloneTrees();
    TTree  *GetCloneTree(TString);
    void    WriteCloneTrees();

    void    SetBranchAddress(TTree *);
    void    SetBranchAddress(TChain *);

//    Int_t   GetEntry(Int_t);
    Int_t   GetEntry(Long64_t);
    Long64_t GetReadEntry();
    Int_t   GetYodaEntry();

    void SetMaxShift(Int_t sh){ maxshift = sh; return;}; // EMILIANO method to change the maxshift variable

    Long64_t GetEntries(){return pam_tree->GetEntries();};
    TChain* GetPamTree(){return pam_tree;};
    TChain* GetRunTree(){return run_tree;};
    TTree*  GetYodaTree();

    TFile*  GetYodaFile(){return l0_file;}; // can be useful to know the name of level0 file we are using or similar things

//  =============
//  DB connection
//  =============
    void SetDBHost(TString str){host=str;};
    void SetDBUser(TString str){user=str;};
    void SetDBPsw(TString str){psw=str;};
    TSQLServer* GetSQLServer(){return dbc;};
    Bool_t SetDBConnection();

//  ========================================================
//  methods needed to retrieve subdetector general variables
//  ========================================================
    void*       GetPointerTo(const char*);
    EventHeader  *GetEventHeader()  { return h0_obj; };

/*     TrkLevel0    *GetTrkLevel0()   { return trk0_obj; }; */
/*     CaloLevel0   *GetCaloLevel0()  { return calo0_obj; }; */
    TrkLevel0    *GetTrkLevel0();
    CaloLevel0   *GetCaloLevel0();


    TrkLevel1    *GetTrkLevel1()  { return trk1_obj; };
    TrkLevel2    *GetTrkLevel2()  { return trk2_obj; };
    TrkHough     *GetTrkHough()   { return trkh_obj; };
    CaloLevel1   *GetCaloLevel1() { return calo1_obj;};
    CaloLevel2   *GetCaloLevel2() { return calo2_obj;};
    ToFLevel2    *GetToFLevel2()  { return tof_obj;  };
    TrigLevel2   *GetTrigLevel2() { return trig_obj; };
    S4Level2     *GetS4Level2()   { return s4_obj;   };
    NDLevel2     *GetNDLevel2()   { return nd_obj;   };
    AcLevel2     *GetAcLevel2()   { return ac_obj;   };
    OrbitalInfo  *GetOrbitalInfo(){ return orb_obj;  };
    GL_RUN       *GetRunInfo()    { return run_obj;  };
    SoftInfo     *GetSoftInfo()   { return soft_obj; }; // Emiliano
    GPamela      *GetGPamela()    { return gp_obj;   };

//  ==============================================
//  methods to retrieve subdetectors stored tracks
//  ==============================================
    TrkTrack*   GetTrkStoredTrack(int seqno){return trk2_obj->TrkLevel2::GetStoredTrack(seqno); };
    CaloTrkVar* GetCaloStoredTrack(int);
    ToFTrkVar*  GetToFStoredTrack(int);
    OrbitalInfoTrkVar*  GetOrbitalInfoStoredTrack(int);
    //
    PamTrack*   GetPamTrackAlong(TrkTrack*);
//	PamTrack*   GetPamTrackAlong(CaloTrkVar*);      //se serve
//	PamTrack*   GetPamTrackAlong(ToFTrkVar*);      //se serve

//  =================================
//  methods to retrieve pamela tracks
//  =================================
    PamTrack*     GetStoredTrack(Int_t);
    //
    void          SortTracks(TString);          //assign value to variable sorted_tracks
    void          SortTracks();          //assign value to variable sorted_tracks
//    TRefArray*    GetTracks();                  //return sorted_tracks
    TClonesArray* GetTracks();                  //return sorted_tracks
    PamTrack*     GetTrack(int);
    PamTrack*     GetTrackImage(int);
    void          SetSortingMethod(TString how);
    TString       GetSortingMethod(){return howtosort;};
    void          SetNucleiSortingThreshold(Float_t nucleithr){ sortthr = nucleithr; return;};
    Float_t       GetNucleiSortingThreshold(){ return sortthr;};

//  =================================
//  other methods
//  =================================
//    Int_t ntrk(){ return trk2_obj->TrkLevel2::ntrk(); };


    Long64_t  GetRunID(){ return irun;};
    Long64_t  GetRunEntryID(){ return irunentry; };

    // -----
    // flags methods
    // -----
    Bool_t IsCAL2(){return CAL2;}; //level2 branch
    Bool_t IsCAL1(){return CAL1;}; //level1 branch
    Bool_t IsCAL0(){return CAL0;}; //yoda

    Bool_t IsTRK2(){return TRK2;}; //level2 branch
    Bool_t IsTRK1(){return TRK1;}; //level1 branch
    Bool_t IsTRKh(){return TRKh;}; //hough branch
    Bool_t IsTRK0(){return TRK0;}; //yoda

    Bool_t IsTOF(){return TOF;};
    Bool_t IsTOF0(){return TOF0;};

    Bool_t IsTRG(){return TRG;};
    Bool_t IsS4(){return S4;};
    Bool_t IsND(){return ND;};
    Bool_t IsAC(){return AC;};
    Bool_t IsORB(){return ORB;};

    Bool_t IsRUN(){return RUN;};

    Bool_t IsGood(Bool_t strict=true);

    Int_t  IsSELLI(){return SELLI;}; //trees of selected events (there is a selection list)
    void  SetSELLI(Int_t selli){SELLI=selli;};

    Bool_t IsGP(){return ISGP;};

    void   SetGP(Bool_t tt){ISGP=tt;};

    void SetDebug(Bool_t set){ DBG=set; TrkParams::SetVerboseMode(); };


    ClassDef(PamLevel2,1);
};

//===============================================================================================
//
//
//
//
//===============================================================================================


#endif

