//-*- mode: c++ -*-
#ifndef BRAT_BrModuleMatchTrack
#define BRAT_BrModuleMatchTrack

//  $Id: BrModuleMatchTrack.h,v 1.12 2002/08/21 15:41:28 ufstasze Exp $
//
///////////////////////////////////////////////////////////////////////
//                                                                   //
//    BrModuleMatchTrack                                             //
//                                                                   //
//    BRAHMS Track Match Class                                       //
//                                                                   //
//    Author  : F.Videbaek (videbaek@bnl.gov)                        //
//    Created : 23/Sep/1998                                          //
//    Version : 1.0                                                  //
//    Changed : November 98.
//              Modified naming using vector classes.                //
//                                                                   //
///////////////////////////////////////////////////////////////////////

//ROOT Classes


//Brat Classes
//

# include "BrModule.h"


#if !defined BRAT_BrSpectrometerTracks
# include "BrSpectrometerTracks.h"
#endif

#if !defined ROOT_TH2
#include "TH2.h"
#endif
#if !defined ROOT_TH1
#include "TH1.h"
#endif

#ifndef ROOT_TClonesArray
#include "TClonesArray.h"
#endif

class BrGeometryDbManager;
class BrDetectorVolume;
class BrMagnetVolume;
class BrDetectorTrack;
class TNtuple;


class BrModuleMatchTrack : public BrModule {
  
public:
  
  BrModuleMatchTrack();
  BrModuleMatchTrack(const Char_t*, const Char_t*);
  BrModuleMatchTrack(const Char_t*, const Char_t*,
                     const Char_t*, const Char_t*, const Char_t*);
  
  virtual ~BrModuleMatchTrack();

  void Init();
  void Event(BrEventNode* InputEventNode, BrEventNode* OutputEventNode);
  void Finish();
  void Clear();
  void CombineFrontBack(BrEventNode* InputEventNode);


  void SetNtuple(Bool_t n = kFALSE)     { fNtuple      = n; }

  TClonesArray * GetMatchedTracks() const {return fTracksFrontBack;}

  void    ListMatchingParameters() const;

  BrDetectorVolume* GetFrontVolume() const {return fFrontVolume;}
  BrDetectorVolume* GetBackVolume()  const {return fBackVolume;}
  BrMagnetVolume* GetMagnetVolume()  const {return fMagnetVolume;}

  void SetMatchDangOffset(Double_t value) {fMatchDangOffset=value;}
  void SetMatchDalyOffset(Double_t value) {fMatchDalyOffset=value;}
  void SetMatchDyOffset(Double_t value) {fMatchDyOffset=value;}

  void SetFiducialCutDx(Double_t value){fFiducialCutdx=value;}
  void SetFiducialCutDy(Double_t value){fFiducialCutdy=value;} 

  Double_t GetSigmaDang()  const { return fSigmaMatchedDang;}
  Double_t GetSigmaDaly()  const { return fSigmaMatchedDaly;}
  Double_t GetSigmaDy()    const { return fSigmaMatchedDy;}
  Double_t GetMatchDangOffset()  const { return fMatchDangOffset;}
  Double_t GetMatchDalyOffset()  const { return fMatchDalyOffset;}
  Double_t GetMatchDyOffset()    const { return fMatchDyOffset;}
  
  Double_t GetSigmaRange() const { return fSigmaRange;}
  Double_t GetSigmaCut() const { return fSigmaCut;}

  Double_t GetFiducialCutDx() const {return fFiducialCutdx;}
  Double_t GetFiducialCutDy() const {return fFiducialCutdy;} 

  void SetSigmaDang(Double_t val)  { fSigmaMatchedDang = val;}
  void SetSigmaDaly(Double_t val)  { fSigmaMatchedDaly = val;}
  void SetSigmaDy(Double_t val)    { fSigmaMatchedDy = val;}
  void SetSigmaRange(Double_t val) { fSigmaRange = val;}
  void SetSigmaCut(Double_t val)   { fSigmaCut = val;}

  void SetRotationFactors(Double_t f=1.0, Double_t b=1.0) {fFrontRot = f; fBackRot =b;}

  void SetHistMomentumRange(Double_t range = 20.0) { fHistMomentumRange= range;}

  void SetOldFiducialCuts()         {fNewFiducialCuts=kFALSE;}

  virtual Char_t* GetSourceVersion() const;
  virtual Char_t* BrModuleMatchTrack::GetHeaderVersion() const {
    return Form("$Source: /afs/rhic/brahms/BRAHMS_CVS/brat/modules/track/combine/BrModuleMatchTrack.h,v $ $Revision: 1.12 $");
  }

  virtual void    Print(Option_t* option="B") const;  

protected:

  void CleanUpTracks();
  void CleanUpSharedBackTracks();
  void CleanUpSharedFrontTracks();
  void SetDefaultParameters();
  void DefineHistograms();
  void CreateClonesArrays();
  void ClearClonesArrays();


private:

  Bool_t MatchesCuts(Double_t dang, Double_t dy, Double_t daly, Double_t p);
  Bool_t GetFiducialStatus(BrDetectorTrack* front,BrDetectorTrack* back);

  BrGeometryDbManager* fGeomDb;       //! Database manager descriptor

  BrDetectorVolume* fFrontVolume;// Volume Descriptor for front tr. chamber
  BrDetectorVolume* fBackVolume;   // Volume Descriptor for back tr. chamber
  BrMagnetVolume* fMagnetVolume; // Volume Descriptor for Magnet

  Double_t fFiducialCutdx; // Fiducal volume cut X (from edge of magnet at entrance/exit)
  Double_t fFiducialCutdy; // Fiducal volume cut Y

  Double_t fMatchDangOffset;     // Effective edge matching angle offset
  Double_t fMatchDalyOffset;     // Effective edge matching cosine alphay offset 
  Double_t fMatchDyOffset;       // Offset for dy matching (cm)

  Double_t fSigmaMatchedDang;  // Fitted sigma for match parameter (Dang) used for selection
  Double_t fSigmaMatchedDaly;  // Fitted sigma for match parameter (Daly) used for selection
  Double_t fSigmaMatchedDy;    // Fitted sigma for match parameter (Dy) used for selection
  Double_t fSigmaRange;        // how many sigmas used for initial selection
  Double_t fSigmaCut;          // how many sigmas for final selection.

  Double_t fFrontRot;        // Rotation of front tracks (to make dAng independent of p)
  Double_t fBackRot;         // Rotation of back tracks (to make dAng independent of p)

  TClonesArray *fTracksFrontBack;  // Results of track matching

  TString fFrontName;
  TString fBackName;
  TString fMagnetName;

  Bool_t fNewFiducialCuts;

  //
  // Statistics
  //
  Int_t fNoEvents;
  Int_t fMatchedTrackSum;

  //
  // Histograms
  //

  Double_t fHistMomentumRange;  // define range for several diagnostic histograms
  TH1F* hFrontTracks;
  TH1F* hBackTracks;
  TH1F* hMatchedTracks;
  TH1F* hGoodMatchedTracks;
  TH1F* hMatchDyAll;
  TH1F* hMatchDxAll;
  TH1F* hMatchDalxAll;
  TH1F* hMatchDalyAll;
  TH1F* hMatchDangAll;
  TH1F* hMatchDyAcpt;
  TH1F* hMatchDxAcpt;
  TH1F* hMatchDangAcpt;
  TH2F* hMatchDangDxAcpt;
  TH2F* hMatchDangDxAll;
  TH2F* hMatchDxDyAll;
  TH2F* hMatchDxDyAcpt;
  TH1F* hMatchDalxAcpt;
  TH1F* hMatchDslAngxAcpt;
  TH1F* hMatchDalyAcpt;

  TH2F* hMatchDalyDyAcpt;
  TH2F* hMatchDalyDyAll;;
  TH2F* hMatchDangTrack;
  TH2F* hMatchDangVsP;
  TH2F* hMatchDyVsP;
  TH1F* hMatchP;
  TH1F* hMatchPl;
  TH1F* hMatchPGood;
  TH1F* hMatchMidX;
  TH1F* hMatchMidY;
  TH1F* hAllMidX;
  TH1F* hAllMidY;
  TH1F* hNoFrontMatch;
  TH1F* hMatchChisqAll;
  TH1F* hMatchChisq;

  TNtuple* fMatchInfo; // correlation between all variables
  Bool_t   fNtuple;      // switch on/off ntuple

 //
 // Field Parameters
 //
  //
  // Simulations parameter access
  //
  Bool_t fFieldParametersRead;
 
public:

  ClassDef(BrModuleMatchTrack,0) // BRAHMS Track Matching Class

};

#endif

//  $Log: BrModuleMatchTrack.h,v $
//  Revision 1.12  2002/08/21 15:41:28  ufstasze
//  Added GetMatchDangOffset(),  GetMatchDalyOffset() and GetMatchDyOffset()
//
//  Revision 1.11  2002/08/15 14:15:04  ufstasze
//  Added GetFigucialCutDy and GetFiducialCutDy to have access to fiducial cuts in BrBfsTrackingModule
//
//  Revision 1.10  2002/08/08 15:35:59  ufstasze
//  Added fiducial cuts that are impose by using SetSwimStatus
//
//  Revision 1.9  2002/04/10 11:16:04  ekman
//  Added fBackRot and fFrontRot members (and corresponding setter method SetRotationFactors(f,b)).
//  The local tracks are rotated by these factors. This is done to avoid momentum dependence of dang.
//  The default is set to 1.0.
//  Added CleanUpSharedBackTracks() and CleanUpSharedFrontTracks(). These methods make sure that
//  only one matched track of all the matched tracks sharing the same front/back track has status kOk.
//
//  Revision 1.8  2001/12/07 21:06:07  videbaek
//  Added Finish method for printing statistics.
//  Added Ntuple diagnostics - off by default. Use SetNtuple(kTRUE) to turn on
//
//  Revision 1.7  2001/11/24 17:20:45  videbaek
//  Added histogram for goo matched tracks
//
//  Revision 1.6  2001/11/05 06:45:41  ouerdane
//  cleaned up this module
//
//  Revision 1.5  2001/10/18 21:41:58  videbaek
//  Add method to be able to set momentum range for matching plots
//  This is set by default to by 20 geV for FS.
//  MRSTracking modules ets range to something more appropriate (5)
//
//  Revision 1.4  2001/08/29 00:59:19  videbaek
//  Add more diagnostic histograms
//
//  Revision 1.3  2001/08/22 18:31:04  ejkim
//  *** empty log message ***
//
//  Revision 1.2  2001/08/13 11:57:39  staszel
//  Some diagnostic histograms added.
//
//  Revision 1.1.1.1  2001/06/21 14:55:11  hagel
//  Initial revision of brat2
//
//  Revision 1.28  2001/06/07 20:36:35  videbaek
//  remove non-used defined flags (OBSOLETE USE_RELATIVE)
//
//  Revision 1.27  2001/06/05 20:13:32  videbaek
//  Added print method. Changed ListParameters to const.
//
//  Revision 1.26  2001/06/01 17:19:12  videbaek
//  This is an update of BrModuleMatchTrack to fix the error for infinite loops in
//  the Ghostbusting. By looking at code as well as trine's comments I decided
//  to do a complete re-write of CleanUpTracks(), and works according to specs.
//  In addition the BrMatchedTracks have added members to save important info
//  on the CleanUp procedure (chisq, and trackgroup) in case one wants to go back
//  and redo, ghostbusting etc.
//
//  Revision 1.25  2001/05/22 16:58:06  videbaek
//  added fct GetSourceVersion() Changed Name to Source
//
//  Revision 1.24  2001/05/09 01:37:03  videbaek
//  Imporved tracking in the magnet matching. See e-mail for further
//  comments. There are also comments in the code.
//  Changed members in BrMatchedTrack. May affect reading of old files.
//
//  Revision 1.23  2001/03/19 22:01:19  videbaek
//  Added offsets in matching
//
//  Revision 1.22  2001/03/01 16:06:12  bramreco
//  add offsets to matchings
//
//  Revision 1.21  2001/01/25 19:46:07  videbaek
//   remove unused fMagnetField
//
//  Revision 1.20  2001/01/17 02:23:32  hagel
//  Change to make work with BRAT v2
//
//  Revision 1.19  2000/12/22 18:37:18  bramreco
//  Add a few more histograms.
//  and
//  USE proper effective edge rather than magnet lenght. Could have caused a small error
//  in the momentum calculation.
//
//  Revision 1.18  2000/12/21 14:58:53  videbaek
//  added histograms and setting of track variables
//
//  Revision 1.17  2000/12/18 21:53:44  ouerdane
//  Made fHelix a pointer to BrHelix,
//  Removed private members fEntranceX, Y, Z etc. Use now BrVector3D fEntrance,
//  etc. Replaced removed members in Getters and Setters by fEntrance.GetX(), etc.
//
//  Revision 1.16  2000/12/16 01:10:52  videbaek
//  Add diagnistic histogram
//
//  Revision 1.15  2000/11/23 01:36:39  brahmlib
//  Cleaned up code a bit.
//
//  Revision 1.14  2000/11/22 21:20:36  videbaek
//  Modification to handle Init() calls properly.
//  Also changes for detector/Magnetvolumes.
//
//  Revision 1.13  2000/10/31 19:38:08  ouerdane
//  A few changes in the matching and global tracking classes:
//  Matching:
//  ---------
//    BrModuleMatchTrack now calculates the length from the track position
//    in the front tracking chamber to the track position to the back
//    tracking chamber. It calculates the helix branch inside the intermediate
//    magnetic field, the entrance and exit points at the magnetic gap front and
//    back planes (in global coordinates).
//    Note that it uses the local track positions given by
//                      BrDetectorTrack::GetPos()
//    The result is stored in a private member of BrMatchedTrack, namely
//    fMatchedTrackLength that a user can get thanks to
//  	            BrMtachedTrack::GetMatchedTrackLength()
//    (the corresponding setter method exists too).
//    the helix object is also stored as a private member of the matched track
//    and is accessible via BrMatchedTrack::GetHelix()
//
//  Global tracking:
//  ---------------
//    BrMRSTrackingModule and BrFFSTrackingModule now calculate:
//      FFS: track length from front plane of D1 to TOF1 plane
//      MRS: track length from TPM1 track position to TOFW panel
//           (gets the matched track length and add the piece from TPM2 to TOFW)
//    The methods are called:
//      FFS: EvalD1ToTOFWTrackLength()
//      MRS: EvalTPM1ToTOFWTrackLength()
//
//    Both of these modules calculate the number of the pointed slat on the
//    time of flight detector (TOFW or TOF1) as well as the coordinates
//    of the track projection on these TOF detectors.
//    The results are stored in private members of BrMRSTrack and BrFFTrack,
//    namely fPointedSlat, fProjOnTOF1 and fProjOnTOFW, fD1ToTOF1TrackLength
//    fTPM1ToTOFWTrackLength. These values are accessible with the getter methods
//    (setters exist too).
//
//  ---------------
//  The previous TrackLength methods have been removed (they were not appropriate
//  because of their location and the assumption concerning the vertex at (0,0,0))
//  Also removed the cxx files BrMRSTrack.cxx and BrFFSTrack.cxx (useless).
//
//  All the points (entrance and exit points in a magnet detector) are accessible.
//  The coordinates are calculated in the global c.s.
//
//  Revision 1.12  2000/09/12 17:35:09  videbaek
//  Added histograms for mid-plane tracking
//
//  Revision 1.11  2000/09/12 16:03:09  videbaek
//  Add more diagnostic histograms to matching code.
//
//  Revision 1.10  2000/09/08 18:34:35  videbaek
//  Change layout of histograms. Mainly concerned with multiple p-ranges
//  one for low p (i.e. MRS) and high P (FS).
//
//  Revision 1.9  2000/05/01 16:24:48  alv
//  Corrected typos in CVS log message for version 1.8
//
//  Revision 1.8  2000/05/01 16:19:35  alv
//  Changed TH1F* to TH2F* in declarations of hMatchDangVsP and hMatchDyVsP
//  Added include statement for TH2.h
//
//  Revision 1.7  2000/04/28 21:18:24  videbaek
//  Updates to BrLocalTrack. Added fit method; Status is changed. Uses
//  MarkAsBad, IsBad instead of fixed 999.
//  Cleanup of BrModuleMatchtrack. Added histohgrams.
//
//  Revision 1.6  1999/09/08 13:43:18  videbaek
//  Include exlicit reference to TH1.h otherwise
//  rootcint fails because there is no other ref to the TH1F class in
//  the generated streamer method.
//
//  Revision 1.5  1999/04/22 17:24:41  videbaek
//  Change include guards. Add Clear method
//
//  Revision 1.4  1999/01/21 23:23:27  hagel
//  1. Changed convention for checking includes.  Current convention is:
//     BRAT_Br...... eg BRAT_BrModule ala ROOT.
//  2. Added CVS logs to .h files that didnt have them.
//  3. Moved checking of include definition to first line for easier reading
//  4. Put checks before all includes in the include files as per BRAT specifications
//  5. Added BrGeantHeader to Geant Makefile
//  6. All changes have been checked to compile on NT ala Cygnus
//
//  Revision 1.3  1999/01/15 16:37:03  videbaek
//  Working version of MRS tracking of mtp1,mtp2 and new general track
//  classes. Changes also added to BrModuleMatchTrack for this reason.
//
//  Revision 1.2  1998/12/21 20:23:12  videbaek
//  Included MRS tracking, and track combine module as part of a more
//  generalized set of Methods and classes.
//
//