]> git.uio.no Git - u/mrichter/AliRoot.git/blobdiff - MUON/AliMUONEventReconstructor.cxx
Pointers initialised to 0 in the default constructors
[u/mrichter/AliRoot.git] / MUON / AliMUONEventReconstructor.cxx
index 2023f4b16a983cae735f7cd2a19aa79acdc89303..5bbc513ca9feedfabc6639f74ad6e11858d77605 100644 (file)
 
 /*
 $Log$
+Revision 1.27  2001/07/27 13:03:12  hristov
+Default Branch split level set to 99
+
+Revision 1.26  2001/05/03 08:11:31  hristov
+stdlib.h included to define exit()
+
+Revision 1.25  2001/04/25 14:50:42  gosset
+Corrections to violations of coding conventions
+
+Revision 1.24  2001/03/30 09:37:58  gosset
+Initialisations of pointers... for GEANT background events in the constructor
+
+Revision 1.23  2001/01/26 21:44:45  morsch
+Use access functions to AliMUONDigit, ...   member data.
+
+Revision 1.22  2001/01/26 20:00:53  hristov
+Major upgrade of AliRoot code
+Revision 1.20  2001/01/08 11:01:02  gosset
+Modifications used for addendum to Dimuon TDR (JP Cussonneau):
+*. MaxBendingMomentum to make both a segment and a track (default 500)
+*. MaxChi2 per degree of freedom to make a track (default 100)
+*. MinBendingMomentum used also to make a track
+   and not only a segment (default 3)
+*. wider roads for track search in stations 1 to 3
+*. extrapolation to actual Z instead of Z(chamber) in FollowTracks
+*. in track fit:
+   - limits on parameters X and Y (+/-500)
+   - covariance matrices in double precision
+   - normalization of covariance matrices before inversion
+   - suppression of Minuit printouts
+*. correction against memory leak (delete extrapHit) in FollowTracks
+*. RMax to 10 degrees with Z(chamber) instead of fixed values;
+   RMin and Rmax cuts suppressed in NewHitForRecFromGEANT,
+   because useless with realistic geometry
+
+Revision 1.19  2000/11/20 11:24:10  gosset
+New package for reconstructed tracks (A. Gheata):
+* tree output in the file "tree_reco.root"
+* display events and make histograms from this file
+
+Revision 1.18  2000/10/26 12:47:03  gosset
+Real distance between chambers of each station taken into account
+for the reconstruction parameters "fSegmentMaxDistBending[5]"
+
+Revision 1.17  2000/10/24 09:26:20  gosset
+Comments updated
+
+Revision 1.16  2000/10/24 09:22:35  gosset
+Method AddHitsForRecFromRawClusters: real Z of raw cluster and not Z of chamber
+
+Revision 1.15  2000/10/12 15:17:30  gosset
+Sign of fSimpleBValue corrected: sign ox Bx and not Bz (thanks to Galina)
+
+Revision 1.14  2000/10/04 18:21:26  morsch
+Include stdlib.h
+
+Revision 1.13  2000/10/02 21:28:09  fca
+Removal of useless dependecies via forward declarations
+
+Revision 1.12  2000/10/02 16:58:29  egangler
+Cleaning of the code :
+-> coding conventions
+-> void Streamers
+-> some useless includes removed or replaced by "class" statement
+
+Revision 1.11  2000/09/22 09:16:33  hristov
+Casting needed on DEC
+
+Revision 1.10  2000/09/19 09:49:50  gosset
+AliMUONEventReconstructor package
+* track extrapolation independent from reco_muon.F, use of AliMagF...
+* possibility to use new magnetic field (automatic from generated root file)
+
+Revision 1.9  2000/07/20 12:45:27  gosset
+New "EventReconstructor..." structure,
+       hopefully more adapted to tree/streamer.
+"AliMUONEventReconstructor::RemoveDoubleTracks"
+       to keep only one track among similar ones.
+
+Revision 1.8  2000/07/18 16:04:06  gosset
+AliMUONEventReconstructor package:
+* a few minor modifications and more comments
+* a few corrections
+  * right sign for Z of raw clusters
+  * right loop over chambers inside station
+  * symmetrized covariance matrix for measurements (TrackChi2MCS)
+  * right sign of charge in extrapolation (ExtrapToZ)
+  * right zEndAbsorber for Branson correction below 3 degrees
+* use of TVirtualFitter instead of TMinuit for AliMUONTrack::Fit
+* no parameter for AliMUONTrack::Fit() but more fit parameters in Track object
+
 Revision 1.7  2000/07/03 12:28:06  gosset
 Printout at the right place after extrapolation to vertex
 
@@ -49,7 +140,7 @@ Revision 1.1.2.1  2000/06/07 14:44:53  gosset
 Addition of files for track reconstruction in C++
 */
 
-//__________________________________________________________________________
+////////////////////////////////////
 //
 // MUON event reconstructor in ALICE
 //
@@ -63,42 +154,30 @@ Addition of files for track reconstruction in C++
 // * MakeEventToBeReconstructed to build the array of hits to be reconstructed
 // * MakeSegments to build the segments
 // * MakeTracks to build the tracks
-//__________________________________________________________________________
+//
+////////////////////////////////////
 
-#include <iostream.h>
+#include <iostream.h> // for cout
+#include <stdlib.h> // for exit()
 
-#include <TRandom.h>
-#include <TFile.h>
+#include <TTree.h>
 
-#include "AliCallf77.h" 
-#include "AliMUONEventReconstructor.h"
 #include "AliMUON.h"
+#include "AliMUONChamber.h"
+#include "AliMUONEventReconstructor.h"
 #include "AliMUONHitForRec.h"
-#include "AliMUONSegment.h"
-#include "AliMUONHit.h"
 #include "AliMUONRawCluster.h"
+#include "AliMUONRecoEvent.h"
+#include "AliMUONSegment.h"
 #include "AliMUONTrack.h"
-#include "AliMUONChamber.h"
 #include "AliMUONTrackHit.h"
-#include "AliRun.h"
-#include "TParticle.h"
-
-#ifndef WIN32 
-# define initfield initfield_
-# define reco_gufld reco_gufld_
-#else 
-# define initfield INITFIELD
-# define reco_gufld RECO_GUFLD
-#endif 
-
-extern "C"
-{
-void type_of_call initfield();
-void type_of_call reco_gufld(Double_t *Coor, Double_t *Field);
-}
+#include "AliMagF.h"
+#include "AliRun.h" // for gAlice
 
 //************* Defaults parameters for reconstruction
 static const Double_t kDefaultMinBendingMomentum = 3.0;
+static const Double_t kDefaultMaxBendingMomentum = 500.0;
+static const Double_t kDefaultMaxChi2 = 100.0;
 static const Double_t kDefaultMaxSigma2Distance = 16.0;
 static const Double_t kDefaultBendingResolution = 0.01;
 static const Double_t kDefaultNonBendingResolution = 0.144;
@@ -138,27 +217,39 @@ AliMUONEventReconstructor::AliMUONEventReconstructor(void)
   // Is 10 the right size ????
   fRecTracksPtr = new TClonesArray("AliMUONTrack", 10);
   fNRecTracks = 0; // really needed or GetEntriesFast sufficient ????
+  // Memory allocation for the TClonesArray of hits on reconstructed tracks
+  // Is 100 the right size ????
+  fRecTrackHitsPtr = new TClonesArray("AliMUONTrack", 100);
+  fNRecTrackHits = 0; // really needed or GetEntriesFast sufficient ????
 
-  // Initialize magnetic field
-  // using Fortran subroutine INITFIELD in "reco_muon.F".
-  // Should rather use AliMagF ???? and remove prototyping ...
-  initfield();
-  // Impression de quelques valeurs
-  Double_t coor[3], field[3];
-  coor[0] = 50.0;
-  coor[1] = 50.0;
-  coor[2] = 950.0;
-  reco_gufld(coor, field);
-  cout << "coor: " << coor[0] << ", " << coor[1] << ", " << coor[2] << endl;
-  cout << "field: " << field[0] << ", " << field[1] << ", " << field[2] << endl;
-  coor[2] = -950.0;
-  reco_gufld(coor, field);
-  cout << "coor: " << coor[0] << ", " << coor[1] << ", " << coor[2] << endl;
-  cout << "field: " << field[0] << ", " << field[1] << ", " << field[2] << endl;
-  coor[2] = -950.0;
+  // Sign of fSimpleBValue according to sign of Bx value at (50,50,950).
+  Float_t b[3], x[3];
+  x[0] = 50.; x[1] = 50.; x[2] = 950.;
+  gAlice->Field()->Field(x, b);
+  fSimpleBValue = TMath::Sign(fSimpleBValue,(Double_t) b[0]);
+  // See how to get fSimple(BValue, BLength, BPosition)
+  // automatically calculated from the actual magnetic field ????
 
   if (fPrintLevel >= 0) {
-    cout << "AliMUONEventReconstructor constructed with defaults" << endl; Dump();}
+    cout << "AliMUONEventReconstructor constructed with defaults" << endl; Dump();
+    cout << endl << "Magnetic field from root file:" << endl;
+    gAlice->Field()->Dump();
+    cout << endl;
+  }
+  
+  // Initializions for GEANT background events
+  fBkgGeantFile = 0;
+  fBkgGeantTK = 0;
+  fBkgGeantParticles = 0;
+  fBkgGeantTH = 0;
+  fBkgGeantHits = 0;
+  fBkgGeantEventNumber = -1;
+  
+  // Initialize to 0 pointers to RecoEvent, tree and tree file
+  fRecoEvent = 0;
+  fEventTree = 0;
+  fTreeFile  = 0;
+  
   return;
 }
 
@@ -177,6 +268,12 @@ AliMUONEventReconstructor & AliMUONEventReconstructor::operator=(const AliMUONEv
 AliMUONEventReconstructor::~AliMUONEventReconstructor(void)
 {
   // Destructor for class AliMUONEventReconstructor
+  if (fTreeFile) {
+     fTreeFile->Close();
+     delete fTreeFile;
+  }
+//  if (fEventTree) delete fEventTree;
+  if (fRecoEvent) delete fRecoEvent;
   delete fHitsForRecPtr; // Correct destruction of everything ???? or delete [] ????
   for (Int_t st = 0; st < kMaxMuonTrackingStations; st++)
     delete fSegmentsPtr[st]; // Correct destruction of everything ????
@@ -189,6 +286,8 @@ void AliMUONEventReconstructor::SetReconstructionParametersToDefaults(void)
   // Set reconstruction parameters to default values
   // Would be much more convenient with a structure (or class) ????
   fMinBendingMomentum = kDefaultMinBendingMomentum;
+  fMaxBendingMomentum = kDefaultMaxBendingMomentum;
+  fMaxChi2 = kDefaultMaxChi2;
   fMaxSigma2Distance = kDefaultMaxSigma2Distance;
 
   AliMUON *pMUON = (AliMUON*) gAlice->GetModule("MUON");
@@ -201,14 +300,10 @@ void AliMUONEventReconstructor::SetReconstructionParametersToDefaults(void)
     if (ch < 4) fRMin[ch] = TMath::Abs((&(pMUON->Chamber(ch)))->Z()) *
                  2.0 * TMath::Pi() / 180.0;
     else fRMin[ch] = 30.0;
+    // maximum radius at 10 degrees and Z of chamber
+    fRMax[ch] = TMath::Abs((&(pMUON->Chamber(ch)))->Z()) *
+                 10.0 * TMath::Pi() / 180.0;
   }
-  // maximum radius
-  // like in TRACKF_STAT (10 degrees ????)
-  fRMax[0] = fRMax[1] = 91.5;
-  fRMax[2] = fRMax[3] = 122.5;
-  fRMax[4] = fRMax[5] = 158.3;
-  fRMax[6] = fRMax[7] = 260.0;
-  fRMax[8] = fRMax[9] = 260.0;
 
   // ******** Parameters for making segments
   // should be parametrized ????
@@ -218,13 +313,19 @@ void AliMUONEventReconstructor::SetReconstructionParametersToDefaults(void)
   // SIGCUT*DYMAX(IZ)
   for (Int_t st = 0; st < kMaxMuonTrackingStations; st++)
     fSegmentMaxDistNonBending[st] = 5. * 0.22;
-  // Maximum distance in bending plane
-  // values from TRACKF_STAT corresponding to (J psi 20cm)
-  fSegmentMaxDistBending[0] = 1.5;
-  fSegmentMaxDistBending[1] = 1.5;
-  fSegmentMaxDistBending[2] = 3.0;
-  fSegmentMaxDistBending[3] = 6.0;
-  fSegmentMaxDistBending[4] = 6.0;
+  // Maximum distance in bending plane:
+  // values from TRACKF_STAT, corresponding to (J psi 20cm),
+  // scaled to the real distance between chambers in a station
+  fSegmentMaxDistBending[0] = 1.5 *
+    ((&(pMUON->Chamber(1)))->Z() - (&(pMUON->Chamber(0)))->Z()) / 20.0;
+  fSegmentMaxDistBending[1] = 1.5 *
+    ((&(pMUON->Chamber(3)))->Z() - (&(pMUON->Chamber(2)))->Z()) / 20.0;
+  fSegmentMaxDistBending[2] = 3.0 *
+    ((&(pMUON->Chamber(5)))->Z() - (&(pMUON->Chamber(4)))->Z()) / 20.0;
+  fSegmentMaxDistBending[3] = 6.0 *
+    ((&(pMUON->Chamber(7)))->Z() - (&(pMUON->Chamber(6)))->Z()) / 20.0;
+  fSegmentMaxDistBending[4] = 6.0 *
+    ((&(pMUON->Chamber(9)))->Z() - (&(pMUON->Chamber(8)))->Z()) / 20.0;
   
   fBendingResolution = kDefaultBendingResolution;
   fNonBendingResolution = kDefaultNonBendingResolution;
@@ -239,23 +340,23 @@ void AliMUONEventReconstructor::SetReconstructionParametersToDefaults(void)
 }
 
 //__________________________________________________________________________
-Double_t AliMUONEventReconstructor::GetImpactParamFromBendingMomentum(Double_t BendingMomentum)
+Double_t AliMUONEventReconstructor::GetImpactParamFromBendingMomentum(Double_t BendingMomentum) const
 {
   // Returns impact parameter at vertex in bending plane (cm),
   // from the signed bending momentum "BendingMomentum" in bending plane (GeV/c),
   // using simple values for dipole magnetic field.
-  // The sign is the sign of the charge.
+  // The sign of "BendingMomentum" is the sign of the charge.
   return (-0.0003 * fSimpleBValue * fSimpleBLength * fSimpleBPosition /
          BendingMomentum);
 }
 
 //__________________________________________________________________________
-Double_t AliMUONEventReconstructor::GetBendingMomentumFromImpactParam(Double_t ImpactParam)
+Double_t AliMUONEventReconstructor::GetBendingMomentumFromImpactParam(Double_t ImpactParam) const
 {
   // Returns signed bending momentum in bending plane (GeV/c),
+  // the sign being the sign of the charge for particles moving forward in Z,
   // from the impact parameter "ImpactParam" at vertex in bending plane (cm),
   // using simple values for dipole magnetic field.
-  // The sign is the sign of the charge.
   return (-0.0003 * fSimpleBValue * fSimpleBLength * fSimpleBPosition /
          ImpactParam);
 }
@@ -400,11 +501,22 @@ void AliMUONEventReconstructor::ResetSegments(void)
 void AliMUONEventReconstructor::ResetTracks(void)
 {
   // To reset the TClonesArray of reconstructed tracks
-  if (fRecTracksPtr) fRecTracksPtr->Clear();
+  if (fRecTracksPtr) fRecTracksPtr->Delete();
+  // Delete in order that the Track destructors are called,
+  // hence the space for the TClonesArray of pointers to TrackHit's is freed
   fNRecTracks = 0;
   return;
 }
 
+  //__________________________________________________________________________
+void AliMUONEventReconstructor::ResetTrackHits(void)
+{
+  // To reset the TClonesArray of hits on reconstructed tracks
+  if (fRecTrackHitsPtr) fRecTrackHitsPtr->Clear();
+  fNRecTrackHits = 0;
+  return;
+}
+
   //__________________________________________________________________________
 void AliMUONEventReconstructor::MakeEventToBeReconstructed(void)
 {
@@ -525,16 +637,17 @@ AliMUONHitForRec* AliMUONEventReconstructor::NewHitForRecFromGEANT(AliMUONHit* H
   // like in Fortran TRACKF_STAT.
   AliMUONHitForRec* hitForRec;
   Double_t bendCoor, nonBendCoor, radius;
-  Int_t chamber = Hit->fChamber - 1; // chamber(0...)
+  Int_t chamber = Hit->Chamber() - 1; // chamber(0...)
   // only in tracking chambers (fChamber starts at 1)
   if (chamber >= kMaxMuonTrackingChambers) return NULL;
   // only if hit is efficient (keep track for checking ????)
   if (gRandom->Rndm() > fEfficiency) return NULL;
   // only if radius between RMin and RMax
-  bendCoor = Hit->fY;
-  nonBendCoor = Hit->fX;
+  bendCoor = Hit->Y();
+  nonBendCoor = Hit->X();
   radius = TMath::Sqrt((bendCoor * bendCoor) + (nonBendCoor * nonBendCoor));
-  if ((radius < fRMin[chamber]) || (radius > fRMax[chamber])) return NULL;
+  // This cut is not needed with a realistic chamber geometry !!!!
+//   if ((radius < fRMin[chamber]) || (radius > fRMax[chamber])) return NULL;
   // new AliMUONHitForRec from GEANT hit and increment number of AliMUONHitForRec's
   hitForRec = new ((*fHitsForRecPtr)[fNHitsForRec]) AliMUONHitForRec(Hit);
   fNHitsForRec++;
@@ -542,6 +655,9 @@ AliMUONHitForRec* AliMUONEventReconstructor::NewHitForRecFromGEANT(AliMUONHit* H
   hitForRec->SetBendingCoor(bendCoor + gRandom->Gaus(0., fBendingResolution));
   hitForRec->SetNonBendingCoor(nonBendCoor
                               + gRandom->Gaus(0., fNonBendingResolution));
+//   // !!!! without smearing
+//   hitForRec->SetBendingCoor(bendCoor);
+//   hitForRec->SetNonBendingCoor(nonBendCoor);
   // more information into HitForRec
   //  resolution: angular effect to be added here ????
   hitForRec->SetBendingReso2(fBendingResolution * fBendingResolution);
@@ -645,11 +761,20 @@ void AliMUONEventReconstructor::AddHitsForRecFromRawClusters(TTree* TR)
   // on the radius between RMin and RMax.
   AliMUONHitForRec *hitForRec;
   AliMUONRawCluster *clus;
-  Int_t iclus, nclus;
+  Int_t iclus, nclus, nTRentries;
   TClonesArray *rawclusters;
   if (fPrintLevel >= 1) cout << "enter AddHitsForRecFromRawClusters" << endl;
   AliMUON *pMUON  = (AliMUON*) gAlice->GetModule("MUON"); // necessary ????
   // Security on MUON ????
+  pMUON->ResetRawClusters();
+  nTRentries = Int_t(TR->GetEntries());
+  if (nTRentries != 1) {
+    cout << "Error in AliMUONEventReconstructor::AddHitsForRecFromRawClusters"
+        << endl;
+    cout << "nTRentries = " << nTRentries << " not equal to 1" << endl;
+    exit(0);
+  }
+  TR->GetEvent(0); // only one entry
   // Loop over tracking chambers
   for (Int_t ch = 0; ch < kMaxMuonTrackingChambers; ch++) {
     // number of HitsForRec to 0 for the chamber
@@ -658,8 +783,8 @@ void AliMUONEventReconstructor::AddHitsForRecFromRawClusters(TTree* TR)
     if (ch == 0) fIndexOfFirstHitForRecPerChamber[ch] = 0;
     else fIndexOfFirstHitForRecPerChamber[ch] = fNHitsForRec;
     rawclusters = pMUON->RawClustAddress(ch);
-    pMUON->ResetRawClusters();
-    TR->GetEvent((Int_t) (TR->GetEntries()) - 1); // to be checked ????
+//     pMUON->ResetRawClusters();
+//     TR->GetEvent((Int_t) (TR->GetEntries()) - 1); // to be checked ????
     nclus = (Int_t) (rawclusters->GetEntries());
     // Loop over (cathode correlated) raw clusters
     for (iclus = 0; iclus < nclus; iclus++) {
@@ -676,9 +801,8 @@ void AliMUONEventReconstructor::AddHitsForRecFromRawClusters(TTree* TR)
       //  original raw cluster
       hitForRec->SetChamberNumber(ch);
       hitForRec->SetHitNumber(iclus);
-      // Z coordinate of the chamber (cm)
-      // could (should) be more exact from chamber geometry ???? 
-      hitForRec->SetZ((&(pMUON->Chamber(ch)))->Z());
+      // Z coordinate of the raw cluster (cm)
+      hitForRec->SetZ(clus->fZ[0]);
       if (fPrintLevel >= 10) {
        cout << "chamber (0...): " << ch <<
          " raw cluster (0...): " << iclus << endl;
@@ -729,7 +853,7 @@ void AliMUONEventReconstructor::MakeSegmentsPerStation(Int_t Station)
   AliMUONSegment *segment;
   Bool_t last2st;
   Double_t bendingSlope, distBend, distNonBend, extBendCoor, extNonBendCoor,
-    impactParam, maxImpactParam;
+      impactParam = 0., maxImpactParam = 0., minImpactParam = 0.; // =0 to avoid compilation warnings.
   AliMUON *pMUON  = (AliMUON*) gAlice->GetModule("MUON"); // necessary ????
   if (fPrintLevel >= 1)
     cout << "enter MakeSegmentsPerStation (0...) " << Station << endl;
@@ -743,6 +867,9 @@ void AliMUONEventReconstructor::MakeSegmentsPerStation(Int_t Station)
     // maximum impact parameter (cm) according to fMinBendingMomentum...
     maxImpactParam =
       TMath::Abs(GetImpactParamFromBendingMomentum(fMinBendingMomentum));
+    // minimum impact parameter (cm) according to fMaxBendingMomentum...
+    minImpactParam =
+      TMath::Abs(GetImpactParamFromBendingMomentum(fMaxBendingMomentum));
   }
   else last2st = kFALSE;
   // extrapolation factor from Z of first chamber to Z of second chamber
@@ -786,7 +913,8 @@ void AliMUONEventReconstructor::MakeSegmentsPerStation(Int_t Station)
       // Conditions "distBend" and "impactParam" correlated for these stations ????
       if ((distBend < fSegmentMaxDistBending[Station]) &&
          (distNonBend < fSegmentMaxDistNonBending[Station]) &&
-         (!last2st || (impactParam < maxImpactParam))) {
+         (!last2st || (impactParam < maxImpactParam)) &&
+         (!last2st || (impactParam > minImpactParam))) {
        // make new segment
        segment = new ((*fSegmentsPtr[Station])[segmentIndex])
          AliMUONSegment(hit1Ptr, hit2Ptr);
@@ -829,11 +957,15 @@ void AliMUONEventReconstructor::MakeTracks(void)
   // To make the tracks,
   // from the list of segments and points in all stations
   if (fPrintLevel >= 1) cout << "enter MakeTracks" << endl;
+  // The order may be important for the following Reset's
   ResetTracks();
+  ResetTrackHits();
   // Look for candidates from at least 3 aligned points in stations(1..) 4 and 5
   MakeTrackCandidates();
   // Follow tracks in stations(1..) 3, 2 and 1
   FollowTracks();
+  // Remove double tracks
+  RemoveDoubleTracks();
   return;
 }
 
@@ -991,12 +1123,14 @@ void AliMUONEventReconstructor::FollowTracks(void)
 {
   // Follow tracks in stations(1..) 3, 2 and 1
   // too long: should be made more modular !!!!
-  AliMUONHitForRec *bestHit, *extrapHit, *hit;
-  AliMUONSegment *bestSegment, *extrapSegment, *segment;
+  AliMUONHitForRec *bestHit, *extrapHit, *extrapCorrHit, *hit;
+  AliMUONSegment *bestSegment, *extrapSegment, *extrapCorrSegment, *segment;
   AliMUONTrack *track, *nextTrack;
   AliMUONTrackParam *trackParam1, trackParam[2], trackParamVertex;
-  Int_t ch, chInStation, chBestHit, iHit, iSegment, station, trackIndex;
+  // -1 to avoid compilation warnings
+  Int_t ch = -1, chInStation, chBestHit = -1, iHit, iSegment, station, trackIndex; 
   Double_t bestChi2, chi2, dZ1, dZ2, dZ3, maxSigma2Distance, mcsFactor;
+  Double_t bendingMomentum, chi2Norm = 0.;
   AliMUON *pMUON = (AliMUON*) gAlice->GetModule("MUON"); // necessary ????
   // local maxSigma2Distance, for easy increase in testing
   maxSigma2Distance = fMaxSigma2Distance;
@@ -1031,6 +1165,7 @@ void AliMUONEventReconstructor::FollowTracks(void)
       // extrapolation to station
       trackParam1->ExtrapToStation(station, trackParam);
       extrapSegment = new AliMUONSegment(); //  empty segment
+      extrapCorrSegment = new AliMUONSegment(); //  empty corrected segment
       // multiple scattering factor corresponding to one chamber
       // and momentum in bending plane (not total)
       mcsFactor = 0.0136 * trackParam1->GetInverseBendingMomentum();
@@ -1050,6 +1185,14 @@ void AliMUONEventReconstructor::FollowTracks(void)
       extrapSegment->UpdateFromStationTrackParam
        (trackParam, mcsFactor, dZ1, dZ2, dZ3, station,
         trackParam1->GetInverseBendingMomentum());
+      // same thing for corrected segment
+      // better to use copy constructor, after checking that it works properly !!!!
+      extrapCorrSegment->SetBendingCoorReso2(fBendingResolution * fBendingResolution);
+      extrapCorrSegment->
+       SetNonBendingCoorReso2(fNonBendingResolution * fNonBendingResolution);
+      extrapCorrSegment->UpdateFromStationTrackParam
+       (trackParam, mcsFactor, dZ1, dZ2, dZ3, station,
+        trackParam1->GetInverseBendingMomentum());
       bestChi2 = 5.0;
       bestSegment = NULL;
       if (fPrintLevel >= 10) {
@@ -1063,7 +1206,20 @@ void AliMUONEventReconstructor::FollowTracks(void)
        // multiple scattering ????
        // separation in 2 functions: Segment and HitForRec ????
        segment = (AliMUONSegment*) ((*fSegmentsPtr[station])[iSegment]);
-       chi2 = segment->NormalizedChi2WithSegment(extrapSegment, maxSigma2Distance);
+       // correction of corrected segment (fBendingCoor and fNonBendingCoor)
+       // according to real Z value of "segment" and slopes of "extrapSegment"
+       extrapCorrSegment->
+         SetBendingCoor(extrapSegment->GetBendingCoor() +
+                        extrapSegment->GetBendingSlope() *
+                        (segment->GetHitForRec1()->GetZ() -
+                         (&(pMUON->Chamber(2 * station)))->Z()));
+       extrapCorrSegment->
+         SetNonBendingCoor(extrapSegment->GetNonBendingCoor() +
+                           extrapSegment->GetNonBendingSlope() *
+                           (segment->GetHitForRec1()->GetZ() -
+                            (&(pMUON->Chamber(2 * station)))->Z()));
+       chi2 = segment->
+         NormalizedChi2WithSegment(extrapCorrSegment, maxSigma2Distance);
        if (chi2 < bestChi2) {
          // update best Chi2 and Segment if better found
          bestSegment = segment;
@@ -1088,6 +1244,7 @@ void AliMUONEventReconstructor::FollowTracks(void)
        // should consider all possibilities ????
        // multiple scattering ???? do about like for extrapSegment !!!!
        extrapHit = new AliMUONHitForRec(); //  empty hit
+       extrapCorrHit = new AliMUONHitForRec(); //  empty corrected hit
        bestChi2 = 3.0;
        bestHit = NULL;
        if (fPrintLevel >= 10) {
@@ -1105,6 +1262,14 @@ void AliMUONEventReconstructor::FollowTracks(void)
          // resolutions from "extrapSegment"
          extrapHit->SetBendingReso2(extrapSegment->GetBendingCoorReso2());
          extrapHit->SetNonBendingReso2(extrapSegment->GetNonBendingCoorReso2());
+         // same things for corrected hit
+         // better to use copy constructor, after checking that it works properly !!!!
+         extrapCorrHit->
+           SetBendingCoor((&(trackParam[chInStation]))->GetBendingCoor());
+         extrapCorrHit->
+           SetNonBendingCoor((&(trackParam[chInStation]))->GetNonBendingCoor());
+         extrapHit->SetBendingReso2(extrapSegment->GetBendingCoorReso2());
+         extrapHit->SetNonBendingReso2(extrapSegment->GetNonBendingCoorReso2());
          // Loop over hits in the chamber
          ch = 2 * station + chInStation;
          for (iHit = fIndexOfFirstHitForRecPerChamber[ch];
@@ -1112,6 +1277,18 @@ void AliMUONEventReconstructor::FollowTracks(void)
                 fNHitsForRecPerChamber[ch];
               iHit++) {
            hit = (AliMUONHitForRec*) ((*fHitsForRecPtr)[iHit]);
+           // correction of corrected hit (fBendingCoor and fNonBendingCoor)
+           // according to real Z value of "hit" and slopes of right "trackParam"
+           extrapCorrHit->
+             SetBendingCoor((&(trackParam[chInStation]))->GetBendingCoor() +
+                            (&(trackParam[chInStation]))->GetBendingSlope() *
+                            (hit->GetZ() -
+                             (&(trackParam[chInStation]))->GetZ()));
+           extrapCorrHit->
+             SetNonBendingCoor((&(trackParam[chInStation]))->GetNonBendingCoor() +
+                               (&(trackParam[chInStation]))->GetNonBendingSlope() *
+                               (hit->GetZ() -
+                                (&(trackParam[chInStation]))->GetZ()));
            // condition for hit not already in segment ????
            chi2 = hit->NormalizedChi2WithHitForRec(extrapHit, maxSigma2Distance);
            if (chi2 < bestChi2) {
@@ -1135,24 +1312,35 @@ void AliMUONEventReconstructor::FollowTracks(void)
          }
        }
        else {
-         // Remove current track candidate and update fNRecTracks
-         // To be checked: recursive delete of TrackHit's !!!!
-         // For cleaner implementation: call track->Remove()
-         // to be coded, with all cleanings,
-         // including links between HitForRec's and TrackHit's !!!!
-         fRecTracksPtr->Remove(track);
-         fNRecTracks--;
+         // Remove current track candidate
+         // and corresponding TrackHit's, ...
+         track->Remove();
          delete extrapSegment;
+         delete extrapCorrSegment;
+         delete extrapHit;
+         delete extrapCorrHit;
          break; // stop the search for this candidate:
          // exit from the loop over station
        }
+       delete extrapHit;
+       delete extrapCorrHit;
       }
       delete extrapSegment;
+      delete extrapCorrSegment;
       // Sort track hits according to increasing Z
       track->GetTrackHitsPtr()->Sort();
       // Update track parameters at first track hit (smallest Z)
       trackParam1 = ((AliMUONTrackHit*)
                     (track->GetTrackHitsPtr()->First()))->GetTrackParam();
+      bendingMomentum = 0.;
+      if (TMath::Abs(trackParam1->GetInverseBendingMomentum()) > 0.)
+       bendingMomentum = TMath::Abs(1/(trackParam1->GetInverseBendingMomentum()));
+      // Track removed if bendingMomentum not in window [min, max]
+      if ((bendingMomentum < fMinBendingMomentum) || (bendingMomentum > fMaxBendingMomentum)) {
+       track->Remove();
+       break; // stop the search for this candidate:
+       // exit from the loop over station 
+      }
       // Track fit
       // with multiple Coulomb scattering if all stations
       if (station == 0) track->SetFitMCS(1);
@@ -1161,6 +1349,18 @@ void AliMUONEventReconstructor::FollowTracks(void)
       track->SetFitNParam(5);  // with 5 parameters (momentum and position)
       track->SetFitStart(1);  // from parameters at first hit
       track->Fit();
+      Double_t numberOfDegFree = (2.0 * track->GetNTrackHits() - 5);
+      if (numberOfDegFree > 0) {
+        chi2Norm =  track->GetFitFMin() / numberOfDegFree;
+      } else {
+       chi2Norm = 1.e10;
+      }
+      // Track removed if normalized chi2 too high
+      if (chi2Norm > fMaxChi2) {
+       track->Remove();
+       break; // stop the search for this candidate:
+       // exit from the loop over station 
+      }
       if (fPrintLevel >= 10) {
        cout << "FollowTracks: track candidate(0..): " << trackIndex
             << " after fit from station(0..): " << station << " to 4" << endl;
@@ -1187,6 +1387,50 @@ void AliMUONEventReconstructor::FollowTracks(void)
   return;
 }
 
+  //__________________________________________________________________________
+void AliMUONEventReconstructor::RemoveDoubleTracks(void)
+{
+  // To remove double tracks.
+  // Tracks are considered identical
+  // if they have at least half of their hits in common.
+  // Among two identical tracks, one keeps the track with the larger number of hits
+  // or, if these numbers are equal, the track with the minimum Chi2.
+  AliMUONTrack *track1, *track2, *trackToRemove;
+  Bool_t identicalTracks;
+  Int_t hitsInCommon, nHits1, nHits2;
+  identicalTracks = kTRUE;
+  while (identicalTracks) {
+    identicalTracks = kFALSE;
+    // Loop over first track of the pair
+    track1 = (AliMUONTrack*) fRecTracksPtr->First();
+    while (track1 && (!identicalTracks)) {
+      nHits1 = track1->GetNTrackHits();
+      // Loop over second track of the pair
+      track2 = (AliMUONTrack*) fRecTracksPtr->After(track1);
+      while (track2 && (!identicalTracks)) {
+       nHits2 = track2->GetNTrackHits();
+       // number of hits in common between two tracks
+       hitsInCommon = track1->HitsInCommon(track2);
+       // check for identical tracks
+       if ((4 * hitsInCommon) >= (nHits1 + nHits2)) {
+         identicalTracks = kTRUE;
+         // decide which track to remove
+         if (nHits1 > nHits2) trackToRemove = track2;
+         else if (nHits1 < nHits2) trackToRemove = track1;
+         else if ((track1->GetFitFMin()) < (track2->GetFitFMin()))
+           trackToRemove = track2;
+         else trackToRemove = track1;
+         // remove it
+         trackToRemove->Remove();
+       }
+       track2 = (AliMUONTrack*) fRecTracksPtr->After(track2);
+      } // track2
+      track1 = (AliMUONTrack*) fRecTracksPtr->After(track1);
+    } // track1
+  }
+  return;
+}
+
   //__________________________________________________________________________
 void AliMUONEventReconstructor::EventDump(void)
 {
@@ -1195,7 +1439,6 @@ void AliMUONEventReconstructor::EventDump(void)
 
   AliMUONTrack *track;
   AliMUONTrackParam *trackParam, *trackParam1;
-  TClonesArray *particles; // pointer to the particle list
   TParticle *p;
   Double_t bendingSlope, nonBendingSlope, pYZ;
   Double_t pX, pY, pZ, x, y, z, c;
@@ -1249,19 +1492,41 @@ void AliMUONEventReconstructor::EventDump(void)
             z, x, y, pX, pY, pZ, c);
   }
   // informations about generated particles
-  particles = gAlice->Particles();
-  np = particles->GetEntriesFast();
+  np = gAlice->GetNtrack();
   printf(" **** number of generated particles: %d  \n", np);
   
   for (Int_t iPart = 0; iPart < np; iPart++) {
-    p = (TParticle*) particles->UncheckedAt(iPart);
+    p = gAlice->Particle(iPart);
     printf(" particle %d: type= %d px= %f py= %f pz= %f pdg= %d\n",
           iPart, p->GetPdgCode(), p->Px(), p->Py(), p->Pz(), p->GetPdgCode());    
   }
   return;
 }
 
-void AliMUONEventReconstructor::Streamer(TBuffer &R__b)
+void AliMUONEventReconstructor::FillEvent()
 {
-    ;
+// Create a new AliMUONRecoEvent, fill its track list, then add it as a
+// leaf in the Event branch of TreeRecoEvent tree
+   cout << "Enter FillEvent() ...\n";
+
+   if (!fRecoEvent) {
+      fRecoEvent = new AliMUONRecoEvent();
+   } else {
+      fRecoEvent->Clear();
+   }
+   //save current directory
+   TDirectory *current =  gDirectory;
+   if (!fTreeFile)  fTreeFile  = new TFile("tree_reco.root", "RECREATE");
+   if (!fEventTree) fEventTree = new TTree("TreeRecoEvent", "MUON reconstructed events");
+   if (fRecoEvent->MakeDumpTracks(fRecTracksPtr)) {
+      if (fPrintLevel > 1) fRecoEvent->EventInfo();
+      TBranch *branch = fEventTree->GetBranch("Event");
+      if (!branch) branch = fEventTree->Branch("Event", "AliMUONRecoEvent", &fRecoEvent, 64000);
+      branch->SetAutoDelete();
+      fTreeFile->cd();
+      fEventTree->Fill();
+      fTreeFile->Write();
+   }
+   // restore directory
+   current->cd();
 }