/**
 * \file TrkLevel2.h
 * \author Elena Vannuccini
 */
#ifndef trklevel2_h
#define trklevel2_h

#include <TObject.h>
#include <TObjArray.h>
#include <TClonesArray.h>
#include <TRefArray.h>
#include <TRef.h>

#include <TrkParams.h>
#include <TrkLevel1.h>

// z-coordinate of track state-vector reference-plane
#define ZINI 23.5   
// (mechanical) z-coordinate of the tracker planes
#define ZTRK6 -22.23
#define ZTRK5 -13.32
#define ZTRK4 -4.42
#define ZTRK3 4.48
#define ZTRK2 13.38
#define ZTRK1 22.28
// (mechanical) x/y-coordinates of magnet cavity
#define XTRKL -8.1
#define XTRKR  8.1
#define YTRKL -6.6
#define YTRKR  6.6

/**
 * \brief Class to describe, by points, a particle trajectory in the apparatus. 
 *
 * The idea is to create it by integrating the equations of motion, given the 
 * track state vector and the z coordinates where to evaluate track position.
 */
// ==================================================================
class Trajectory : public TObject{
 private:

 public:

    int npoint; ///< number of evaluated points along the trajectory
    float* x;   ///< x coordinates 
    float* y;   ///< y coordinates 
    float* z;   ///< z coordinates 
    float* thx; ///< x projected angle 
    float* thy; ///< y projected angle
    float* tl;  ///< track length

    Trajectory();
    Trajectory(int n);
    Trajectory(int n, float* pz);
    ~Trajectory(){Delete();};
    void Dump();
    void Delete();

    int DoTrack2(float* al);
    float GetLength(){float l=0; for(int i=0; i<npoint;i++)l=l+tl[i]; return l;};
    float GetLength(int,int);

    ClassDef(Trajectory,2);

};
/**
 * \brief Class to describe fitted tracks. 
 *
 * A track is defined by the measured coordinates associated to it, the 
 * track status vector, plus other quantities.
 * A track may have an "image", due to the ambiguity in the y view.
 *
 * Cluster flags: xgood[6], ygood[6]
 * 
 * xgood/ygood = +/- 0lsccccccc
 *                |   |||------- ID (1-7483647) of the included cluster  
 *                |   ||-------- sensor number (1,2   - increasing y)
 *                |   |--------- ladder number (1,2,3 - increasing x)
 *                |------------- does-not/does include bad strips
 */
// ==================================================================
class TrkTrack : public TObject {

private:

    int   seqno;           ///<stored track sequential number
    int   image;           ///<sequential number of track-image
	
public:

    float al[5];           ///<TRACK STATE VECTOR 
    float coval[5][5];     ///<covariance matrix 
    int   xgood[6];        ///<cluster flag for x-view (0 = view not included in the fit) 
    int   ygood[6];        ///<cluster flag for y-view (0 = view not included in the fit) 
    float xm[6];           ///<measured x coordinates
    float ym[6];           ///<measured y coordinates 
    float zm[6];           ///<measured z coordinates 
    float resx[6];         ///<spatial resolution on X view
    float resy[6];         ///<spatial resolution on y view
    float tailx[6];        ///<spatial resolution tail on X view
    float taily[6];        ///<spatial resolution tail on y view
    float chi2;            ///<chi2
    int   nstep;           ///<n. step
    float xv[6];           ///<calculated x coordinates
    float yv[6];           ///<calculated y coordinates
    float zv[6];           ///<calculated z coordinates
    float axv[6];          ///<calculated angles (deg) on x view
    float ayv[6];          ///<calculated angles (deg) on y view
    float dedx_x[6];       ///<dE/dx in MIP (<0 if saturated)
    float dedx_y[6];       ///<dE/dx in MIP (<0 if saturated) 

    TrkTrack();
    TrkTrack(const TrkTrack&);

    ~TrkTrack(){ Delete(); };
	
    void Dump();
    void Clear();
    void Clear(Option_t *option){Clear();};
    void Delete();
    void Copy(TrkTrack&);
//    void Set();

    Int_t  GetSeqNo(){return seqno;}        ///< Returns the track sequential number
    Int_t  GetImageSeqNo(){return image;}   ///< Returns the track image sequential number
    Bool_t HasImage(){return !(image==-1);} ///< Returns true if the track has an image
    int DoTrack(Trajectory* t);   			///< Evaluates the trajectory in the apparatus.
    int DoTrack2(Trajectory* t);   			///< Evaluates the trajectory in the apparatus.
    float BdL(){return 0;};					///< Evaluates the integral of B*dL along the track.
    Int_t GetNX(){Int_t n=0; for(Int_t i=0; i<6; i++)n+=(Int_t)XGood(i); return n;}; 
    Int_t GetNY(){Int_t n=0; for(Int_t i=0; i<6; i++)n+=(Int_t)YGood(i); return n;};
    Int_t GetNtot(){return GetNX()+GetNY();};
    Float_t GetRigidity();
    Float_t GetDeflection();
    Bool_t IsSaturated(int,int);
    Bool_t IsSaturated(int);
    Bool_t IsSaturated();
    Bool_t IsBad(int,int);
    Float_t GetDEDX();
    Float_t GetDEDX(int);
    Float_t GetDEDX(int,int);
    Int_t GetLeverArmX();
    Int_t GetLeverArmY();

    void SetMeasure(double *xmeas, double *ymeas, double *zmeas);
    void SetResolution(double *rx, double *ry);
    void SetGood(int *xg, int *yg);
    void LoadField(TString s);
    void Fit(double pfixed, int& fail, int iprint, int froml1);
    void Fit(double pfixed, int& fail, int iprint){ Fit(pfixed,fail,iprint,0); };
    void FitReset();
    void SetTrackingMode(int trackmode);
    void SetPrecisionFactor(double fact);
    void SetStepMin(int istepmin);

    void EvaluateClusterPositions();

    void FillMiniStruct(cMini2track&);
    void SetFromMiniStruct(cMini2track*);
    
    Int_t GetClusterX_ID(int ip);
    Int_t GetClusterY_ID(int ip);
    Int_t GetLadder(int ip);
    Int_t GetSensor(int ip);
    Bool_t XGood(int ip){ return GetClusterX_ID(ip)!=-1; };
    Bool_t YGood(int ip){ return GetClusterY_ID(ip)!=-1; };
    void ResetXGood(int ip){ xgood[ip]=0; };
    void ResetYGood(int ip){ ygood[ip]=0; };
    void SetXGood(int ip, int clid, int is);
    void SetYGood(int ip, int clid, int is);

    Bool_t BadClusterX(int ip){ return IsBad(ip,0); };
    Bool_t BadClusterY(int ip){ return IsBad(ip,1); };

    Bool_t SaturatedClusterX(int ip){ return IsSaturated(ip,0); };
    Bool_t SaturatedClusterY(int ip){ return IsSaturated(ip,1); };

    TrkTrack* GetTrkTrack(){return this;};

    friend class TrkLevel2;

    ClassDef(TrkTrack,3);

};
/**
 * \brief Class to describe single clusters ("singlets"). 
 *
 * Single clusters are clusters not associated to any track.
 */
class TrkSinglet : public TObject {

private:
	

public:
	
    int plane;       ///<plane 
    float coord[2];  ///<coordinate (on sensor 1 and 2)
    float sgnl;      ///<cluster signal in MIP (<0 if saturated)

    TrkSinglet();
    TrkSinglet(const TrkSinglet&);
    ~TrkSinglet(){Delete();};

    void Dump();
    void Clear();
    void Clear(Option_t *option){Clear();};
    void Delete(){Clear();};
    Float_t GetSignal(){return fabs(sgnl);}
    Bool_t IsSaturated(){return (sgnl<0); };
	
    friend class TrkLevel2;

    ClassDef(TrkSinglet,3);

};

/**
 * \brief Class to describe tracker LEVEL2 data.
 *
 * A tracker events is defined by some general variables, plus the collection of all the fitted tracks and all 
 * single clusters on X and Y views. 
 * Tracks and single clusters ("singlets") are described by the classes TrkTrack and TrkSinglet respectivelly.
 * 
 * Each track may have an "image", due to the ambiguity on the Y view, which is stored also. 
 * Thus, the number of stored tracks ( ntrk() ) differs from the number of "physical" tracks ( GetNTracks() ). 
 * Proper methods allow to sort tracks and select the physical ones ( GetTracks() ).
 */
class TrkLevel2 : public TObject {

 private:
 
 public:

    Int_t         good[12];       ///< event status
    UInt_t        VKmask[12];     ///< Viking-chip mask
    UInt_t        VKflag[12];     ///< Viking-chip flag

    TClonesArray *Track;        ///< fitted tracks
    TClonesArray *SingletX;     ///< x singlets
    TClonesArray *SingletY;     ///< y singlets

    TrkLevel2();
//    TrkLevel2(cTrkLevel2 *);
    ~TrkLevel2(){Delete();};
	
    void Clear();
    void Clear(Option_t *option){Clear();};
    void Delete();
    void Set();
    
    int ntrk() {return Track->GetEntries();}    ///< number of stored track
    int nclsx(){return SingletX->GetEntries();} ///< number of x singlets 
    int nclsy(){return SingletY->GetEntries();} ///< number of y singlets 

    void Dump();
    void SetFromLevel2Struct(cTrkLevel2 *, TrkLevel1 *);
    void SetFromLevel2Struct(cTrkLevel2 *s2){ SetFromLevel2Struct(s2, NULL);          };
    void SetFromLevel2Struct(TrkLevel1 *l1) { SetFromLevel2Struct(&level2event_, l1); };    
    void SetFromLevel2Struct()              { SetFromLevel2Struct(&level2event_);     };    
    void GetLevel2Struct(cTrkLevel2 *) const;
    void LoadField(TString);
    float GetBX(float* v){return TrkParams::GetBX(v);};///< Bx (kGauss)
    float GetBY(float* v){return TrkParams::GetBY(v);};///< By (kGauss)
    float GetBZ(float* v){return TrkParams::GetBZ(v);};///< Bz (kGauss)
    Float_t GetZTrk(Int_t);
    Float_t GetXTrkLeft(){return XTRKL;};
    Float_t GetXTrkRight(){return XTRKR;};
    Float_t GetYTrkLeft(){return YTRKL;};
    Float_t GetYTrkRight(){return YTRKR;};
    
    Bool_t IsMaskedVK(int,int);
    Bool_t GetVKMask(int,int);
    Bool_t GetVKFlag(int,int);

    TrkSinglet   *GetSingletX(int);
    TrkSinglet   *GetSingletY(int);
    
    TrkTrack     *GetStoredTrack(int i);
    Int_t         GetSeqNo(Int_t i)  {return (((TrkTrack *)Track->At(i))->seqno);}; ///< Returns track sequential number

    TRefArray *GetTracks_NFitSorted();
    TRefArray *GetTracks(){return this->GetTracks_NFitSorted();};
    
    Int_t     GetNTracks();
    TrkTrack* GetTrack(int i);
    TrkTrack* GetTrackImage(int i);
    
    TrkLevel2*    GetTrkLevel2(){return this;}
    TClonesArray* GetTrackArray(){return Track;};///< returns pointer to the track array
    
    ClassDef(TrkLevel2,3);

};

#endif
