]> git.uio.no Git - u/mrichter/AliRoot.git/blobdiff - MUON/AliMUONEventReconstructor.cxx
cosz corrected (was always positive).
[u/mrichter/AliRoot.git] / MUON / AliMUONEventReconstructor.cxx
index 360bf1bea389ae7bf49c59cfdbd307e93d856bf8..de5f4207f5baa346814a5726d54242e024a01abb 100644 (file)
 
 /*
 $Log$
+Revision 1.31  2002/10/23 07:24:56  alibrary
+Introducing Riostream.h
+
+Revision 1.30  2002/10/14 14:57:29  hristov
+Merging the VirtualMC branch to the main development branch (HEAD)
+
+Revision 1.28.8.1  2002/10/11 06:56:47  hristov
+Updating VirtualMC to v3-09-02
+
+Revision 1.29  2002/09/20 13:32:26  cussonno
+Minor bugs in the definition of the bending impact parameter corrected (thanks to A. Zinchenko)
+
+Revision 1.28  2001/08/31 06:50:11  gosset
+Different handling of TreeR for track reconstruction from raw clusters
+
+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
+
+Revision 1.6  2000/06/30 12:01:06  gosset
+Correction for hit search in the right chamber (JPC)
+
+Revision 1.5  2000/06/30 10:15:48  gosset
+Changes to EventReconstructor...:
+precision fit with multiple Coulomb scattering;
+extrapolation to vertex with Branson correction in absorber (JPC)
+
+Revision 1.4  2000/06/27 14:11:36  gosset
+Corrections against violations of coding conventions
+
+Revision 1.3  2000/06/16 07:27:08  gosset
+To remove problem in running RuleChecker, like in MUON-dev
+
+Revision 1.1.2.5  2000/06/16 07:00:26  gosset
+To remove problem in running RuleChecker
+
 Revision 1.1.2.4  2000/06/12 08:00:07  morsch
 Dummy streamer to solve CINT compilation problem (to be investigated !)
 
@@ -29,7 +155,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
 //
@@ -43,58 +169,49 @@ 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 <Riostream.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"
-
-#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
+#include "AliMUONTrackK.h" //AZ
+#include <TMatrixD.h> //AZ
 
 //************* Defaults parameters for reconstruction
-static const Double_t DefaultMinBendingMomentum = 3.0;
-static const Double_t DefaultMaxSigma2Distance = 16.0;
-static const Double_t DefaultBendingResolution = 0.01;
-static const Double_t DefaultNonBendingResolution = 0.144;
-static const Double_t DefaultChamberThicknessInX0 = 0.03;
+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;
+static const Double_t kDefaultChamberThicknessInX0 = 0.03;
 // Simple magnetic field:
 // Value taken from macro MUONtracking.C: 0.7 T, hence 7 kG
 // Length and Position from reco_muon.F, with opposite sign:
 // Length = ZMAGEND-ZCOIL
 // Position = (ZMAGEND+ZCOIL)/2
 // to be ajusted differently from real magnetic field ????
-static const Double_t DefaultSimpleBValue = 7.0;
-static const Double_t DefaultSimpleBLength = 428.0;
-static const Double_t DefaultSimpleBPosition = 1019.0;
-static const Int_t DefaultRecGeantHits = 0;
-static const Double_t DefaultEfficiency = 0.95;
+static const Double_t kDefaultSimpleBValue = 7.0;
+static const Double_t kDefaultSimpleBLength = 428.0;
+static const Double_t kDefaultSimpleBPosition = 1019.0;
+static const Int_t kDefaultRecGeantHits = 0;
+static const Double_t kDefaultEfficiency = 0.95;
 
-static const Int_t DefaultPrintLevel = 0;
+static const Int_t kDefaultPrintLevel = 0;
 
 ClassImp(AliMUONEventReconstructor) // Class implementation in ROOT context
 
@@ -103,13 +220,14 @@ AliMUONEventReconstructor::AliMUONEventReconstructor(void)
 {
   // Constructor for class AliMUONEventReconstructor
   SetReconstructionParametersToDefaults();
+  fTrackMethod = 1; //AZ - tracking method (1-default, 2-Kalman)
   // Memory allocation for the TClonesArray of hits for reconstruction
   // Is 10000 the right size ????
   fHitsForRecPtr = new TClonesArray("AliMUONHitForRec", 10000);
   fNHitsForRec = 0; // really needed or GetEntriesFast sufficient ????
   // Memory allocation for the TClonesArray's of segments in stations
   // Is 2000 the right size ????
-  for (Int_t st = 0; st < MAX_MUON_TRACKING_STATIONS; st++) {
+  for (Int_t st = 0; st < kMaxMuonTrackingStations; st++) {
     fSegmentsPtr[st] = new TClonesArray("AliMUONSegment", 2000);
     fNSegments[st] = 0; // really needed or GetEntriesFast sufficient ????
   }
@@ -117,36 +235,65 @@ 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;
 }
 
+AliMUONEventReconstructor::AliMUONEventReconstructor (const AliMUONEventReconstructor& Reconstructor)
+{
+  // Dummy copy constructor
+}
+
+AliMUONEventReconstructor & AliMUONEventReconstructor::operator=(const AliMUONEventReconstructor& Reconstructor)
+{
+  // Dummy assignment operator
+    return *this;
+}
+
   //__________________________________________________________________________
 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 < MAX_MUON_TRACKING_STATIONS; st++)
+  for (Int_t st = 0; st < kMaxMuonTrackingStations; st++)
     delete fSegmentsPtr[st]; // Correct destruction of everything ????
   return;
 }
@@ -156,27 +303,25 @@ void AliMUONEventReconstructor::SetReconstructionParametersToDefaults(void)
 {
   // Set reconstruction parameters to default values
   // Would be much more convenient with a structure (or class) ????
-  fMinBendingMomentum = DefaultMinBendingMomentum;
-  fMaxSigma2Distance = DefaultMaxSigma2Distance;
+  fMinBendingMomentum = kDefaultMinBendingMomentum;
+  fMaxBendingMomentum = kDefaultMaxBendingMomentum;
+  fMaxChi2 = kDefaultMaxChi2;
+  fMaxSigma2Distance = kDefaultMaxSigma2Distance;
 
-  AliMUON *MUON = (AliMUON*) gAlice->GetModule("MUON");
+  AliMUON *pMUON = (AliMUON*) gAlice->GetModule("MUON");
   // ******** Parameters for making HitsForRec
   // minimum radius,
   // like in TRACKF_STAT:
   // 2 degrees for stations 1 and 2, or ch(0...) from 0 to 3;
   // 30 cm for stations 3 to 5, or ch(0...) from 4 to 9
-  for (Int_t ch = 0; ch < MAX_MUON_TRACKING_CHAMBERS; ch++) {
-    if (ch < 4) fRMin[ch] = TMath::Abs((&(MUON->Chamber(ch)))->Z()) *
+  for (Int_t ch = 0; ch < kMaxMuonTrackingChambers; ch++) {
+    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 ????
@@ -184,46 +329,52 @@ void AliMUONEventReconstructor::SetReconstructionParametersToDefaults(void)
   // Maximum distance in non bending plane
   // 5 * 0.22 just to remember the way it was made in TRACKF_STAT
   // SIGCUT*DYMAX(IZ)
-  for (Int_t st = 0; st < MAX_MUON_TRACKING_STATIONS; st++)
+  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 = DefaultBendingResolution;
-  fNonBendingResolution = DefaultNonBendingResolution;
-  fChamberThicknessInX0 = DefaultChamberThicknessInX0;
-  fSimpleBValue = DefaultSimpleBValue;
-  fSimpleBLength = DefaultSimpleBLength;
-  fSimpleBPosition = DefaultSimpleBPosition;
-  fRecGeantHits = DefaultRecGeantHits;
-  fEfficiency = DefaultEfficiency;
-  fPrintLevel = DefaultPrintLevel;
+  fBendingResolution = kDefaultBendingResolution;
+  fNonBendingResolution = kDefaultNonBendingResolution;
+  fChamberThicknessInX0 = kDefaultChamberThicknessInX0;
+  fSimpleBValue = kDefaultSimpleBValue;
+  fSimpleBLength = kDefaultSimpleBLength;
+  fSimpleBPosition = kDefaultSimpleBPosition;
+  fRecGeantHits = kDefaultRecGeantHits;
+  fEfficiency = kDefaultEfficiency;
+  fPrintLevel = kDefaultPrintLevel;
   return;
 }
 
 //__________________________________________________________________________
-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);
 }
@@ -347,7 +498,7 @@ void AliMUONEventReconstructor::ResetHitsForRec(void)
   // and the index of the first HitForRec per chamber
   if (fHitsForRecPtr) fHitsForRecPtr->Clear();
   fNHitsForRec = 0;
-  for (Int_t ch = 0; ch < MAX_MUON_TRACKING_CHAMBERS; ch++)
+  for (Int_t ch = 0; ch < kMaxMuonTrackingChambers; ch++)
     fNHitsForRecPerChamber[ch] = fIndexOfFirstHitForRecPerChamber[ch] = 0;
   return;
 }
@@ -357,7 +508,7 @@ void AliMUONEventReconstructor::ResetSegments(void)
 {
   // To reset the TClonesArray of segments and the number of Segments
   // for all stations
-  for (Int_t st = 0; st < MAX_MUON_TRACKING_STATIONS; st++) {
+  for (Int_t st = 0; st < kMaxMuonTrackingStations; st++) {
     if (fSegmentsPtr[st]) fSegmentsPtr[st]->Clear();
     fNSegments[st] = 0;
   }
@@ -368,11 +519,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)
 {
@@ -400,14 +562,14 @@ void AliMUONEventReconstructor::MakeEventToBeReconstructed(void)
     // Security on MUON ????
     // TreeR assumed to be be "prepared" in calling function
     // by "MUON->GetTreeR(nev)" ????
-    TTree *TR = gAlice->TreeR();
-    AddHitsForRecFromRawClusters(TR);
+    TTree *treeR = gAlice->TreeR();
+    AddHitsForRecFromRawClusters(treeR);
     // No sorting: it is done automatically in the previous function
   }
   if (fPrintLevel >= 10) {
     cout << "end of MakeEventToBeReconstructed" << endl;
     cout << "NHitsForRec: " << fNHitsForRec << endl;
-    for (Int_t ch = 0; ch < MAX_MUON_TRACKING_CHAMBERS; ch++) {
+    for (Int_t ch = 0; ch < kMaxMuonTrackingChambers; ch++) {
       cout << "chamber(0...): " << ch
           << "  NHitsForRec: " << fNHitsForRecPerChamber[ch]
           << "  index(first HitForRec): " << fIndexOfFirstHitForRecPerChamber[ch]
@@ -428,26 +590,42 @@ void AliMUONEventReconstructor::AddHitsForRecFromGEANT(TTree *TH)
 {
   // To add to the list of hits for reconstruction
   // the GEANT signal hits from a hit tree TH.
+  Int_t hitBits, chamBits; //AZ
   if (fPrintLevel >= 2)
     cout << "enter AddHitsForRecFromGEANT with TH: " << TH << endl;
   if (TH == NULL) return;
-  AliMUON *MUON  = (AliMUON*) gAlice->GetModule("MUON"); // necessary ????
+  AliMUON *pMUON  = (AliMUON*) gAlice->GetModule("MUON"); // necessary ????
   // Security on MUON ????
   // See whether it could be the same for signal and background ????
   // Loop over tracks in tree
   Int_t ntracks = (Int_t) TH->GetEntries();
   if (fPrintLevel >= 2)
     cout << "ntracks: " << ntracks << endl;
+  fMuons = 0; //AZ
   for (Int_t track = 0; track < ntracks; track++) {
     gAlice->ResetHits();
     TH->GetEvent(track);
     // Loop over hits
     Int_t hit = 0;
-    for (AliMUONHit* mHit = (AliMUONHit*) MUON->FirstHit(-1); 
+    hitBits = 0; // AZ
+    chamBits = 0; // AZ
+    Int_t itrack = track; //AZ
+    for (AliMUONHit* mHit = (AliMUONHit*) pMUON->FirstHit(-1); 
         mHit;
-        mHit = (AliMUONHit*) MUON->NextHit(), hit++) {
-      NewHitForRecFromGEANT(mHit,track, hit, 1);
+        mHit = (AliMUONHit*) pMUON->NextHit(), hit++) {
+      Int_t ipart = TMath::Abs ((Int_t) mHit->Particle()); //AZ
+      //itrack = mHit->Track(); //AZ
+      //AZNewHitForRecFromGEANT(mHit,track, hit, 1);
+      if (NewHitForRecFromGEANT(mHit,track, hit, 1) && ipart == 13
+      //if (NewHitForRecFromGEANT(mHit,itrack-1, hit, 1) && ipart == 13 
+          && itrack <= 2) chamBits |= BIT(mHit->Chamber()-1); //AZ - set bit
     } // end of hit loop
+    if (chamBits&3 && chamBits>>2&3 && chamBits>>4&3 && chamBits>>6&3 && 
+        chamBits>>8&3 && ((chamBits>>6&3)==3 || (chamBits>>8&3)==3)) 
+      fMuons += 1; //AZ
+    //if (chamBits&3 && chamBits>>2&3 && chamBits>>4&3 && chamBits>>6&3 && 
+    //      chamBits>>8&3 && ((chamBits>>6&3)==3 || (chamBits>>8&3)==3) && 
+    //      ((chamBits&3)==3 || (chamBits>>2&3)==3)) fMuons += 1;
   } // end of track loop
   return;
 }
@@ -493,16 +671,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 >= MAX_MUON_TRACKING_CHAMBERS) return NULL;
+  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++;
@@ -510,6 +689,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);
@@ -534,7 +716,7 @@ void AliMUONEventReconstructor::SortHitsForRecWithIncreasingChamber()
   // Update the information for HitsForRec per chamber too.
   Int_t ch, nhits, prevch;
   fHitsForRecPtr->Sort();
-  for (ch = 0; ch < MAX_MUON_TRACKING_CHAMBERS; ch++) {
+  for (ch = 0; ch < kMaxMuonTrackingChambers; ch++) {
     fNHitsForRecPerChamber[ch] = 0;
     fIndexOfFirstHitForRecPerChamber[ch] = 0;
   }
@@ -569,7 +751,7 @@ void AliMUONEventReconstructor::SortHitsForRecWithIncreasingChamber()
 //   AliMUON *MUON  = (AliMUON*) gAlice->GetModule("MUON"); // necessary ????
 //   // Security on MUON ????
 //   // Loop over tracking chambers
-//   for (Int_t ch = 0; ch < MAX_MUON_TRACKING_CHAMBERS; ch++) {
+//   for (Int_t ch = 0; ch < kMaxMuonTrackingChambers; ch++) {
 //     // number of HitsForRec to 0 for the chamber
 //     fNHitsForRecPerChamber[ch] = 0;
 //     // index of first HitForRec for the chamber
@@ -613,21 +795,30 @@ 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 *MUON  = (AliMUON*) gAlice->GetModule("MUON"); // necessary ????
+  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 < MAX_MUON_TRACKING_CHAMBERS; ch++) {
+  for (Int_t ch = 0; ch < kMaxMuonTrackingChambers; ch++) {
     // number of HitsForRec to 0 for the chamber
     fNHitsForRecPerChamber[ch] = 0;
     // index of first HitForRec for the chamber
     if (ch == 0) fIndexOfFirstHitForRecPerChamber[ch] = 0;
     else fIndexOfFirstHitForRecPerChamber[ch] = fNHitsForRec;
-    rawclusters = MUON->RawClustAddress(ch);
-    MUON->ResetRawClusters();
-    TR->GetEvent((Int_t) (TR->GetEntries()) - 1); // to be checked ????
+    rawclusters = pMUON->RawClustAddress(ch);
+//     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++) {
@@ -644,9 +835,8 @@ void AliMUONEventReconstructor::AddHitsForRecFromRawClusters(TTree* TR)
       //  original raw cluster
       hitForRec->SetChamberNumber(ch);
       hitForRec->SetHitNumber(iclus);
-      // Z coordinate of the chamber (cm) with sign opposite to GEANT sign
-      // could (should) be more exact from chamber geometry ???? 
-      hitForRec->SetZ(-(&(MUON->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;
@@ -655,6 +845,7 @@ void AliMUONEventReconstructor::AddHitsForRecFromRawClusters(TTree* TR)
        hitForRec->Dump();}
     } // end of cluster loop
   } // end of chamber loop
+  SortHitsForRecWithIncreasingChamber(); //AZ 
   return;
 }
 
@@ -666,11 +857,13 @@ void AliMUONEventReconstructor::MakeSegments(void)
   if (fPrintLevel >= 1) cout << "enter MakeSegments" << endl;
   ResetSegments();
   // Loop over stations
-  for (Int_t st = 0; st < MAX_MUON_TRACKING_STATIONS; st++)
+  Int_t nb = (fTrackMethod == 2) ? 3 : 0; //AZ
+  //AZ for (Int_t st = 0; st < kMaxMuonTrackingStations; st++)
+  for (Int_t st = nb; st < kMaxMuonTrackingStations; st++) //AZ
     MakeSegmentsPerStation(st); 
   if (fPrintLevel >= 10) {
     cout << "end of MakeSegments" << endl;
-    for (Int_t st = 0; st < MAX_MUON_TRACKING_STATIONS; st++) {
+    for (Int_t st = 0; st < kMaxMuonTrackingStations; st++) {
       cout << "station(0...): " << st
           << "  Segments: " << fNSegments[st]
           << endl;
@@ -697,8 +890,8 @@ void AliMUONEventReconstructor::MakeSegmentsPerStation(Int_t Station)
   AliMUONSegment *segment;
   Bool_t last2st;
   Double_t bendingSlope, distBend, distNonBend, extBendCoor, extNonBendCoor,
-    impactParam, maxImpactParam;
-  AliMUON *MUON  = (AliMUON*) gAlice->GetModule("MUON"); // necessary ????
+      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;
   // first and second chambers (0...) in the station
@@ -711,12 +904,15 @@ 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
   // dZ to be changed to take into account fine structure of chambers ????
   Double_t extrapFact =
-    (&(MUON->Chamber(ch2)))->Z() / (&(MUON->Chamber(ch1)))->Z();
+    (&(pMUON->Chamber(ch2)))->Z() / (&(pMUON->Chamber(ch1)))->Z();
   // index for current segment
   Int_t segmentIndex = 0;
   // Loop over HitsForRec in the first chamber of the station
@@ -747,14 +943,15 @@ void AliMUONEventReconstructor::MakeSegmentsPerStation(Int_t Station)
          (hit1Ptr->GetZ() - hit2Ptr->GetZ());
        // absolute value of impact parameter
        impactParam =
-         TMath::Abs(hit1Ptr->GetBendingCoor() - hit2Ptr->GetZ() * bendingSlope);
+         TMath::Abs(hit1Ptr->GetBendingCoor() - hit1Ptr->GetZ() * bendingSlope);
       }
       // check for distances not too large,
       // and impact parameter not too big if stations downstream of the dipole.
       // 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);
@@ -797,11 +994,25 @@ 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();
-  // 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();
+  ResetTrackHits();
+  if (fTrackMethod == 2) { //AZ - Kalman filter
+    MakeTrackCandidatesK();
+    // Follow tracks in stations(1..) 3, 2 and 1
+    FollowTracksK();
+    // Remove double tracks
+    RemoveDoubleTracksK();
+    // Propagate tracks to the vertex thru absorber
+    GoToVertex();
+  } else { //AZ
+    // 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;
 }
 
@@ -832,6 +1043,7 @@ Int_t AliMUONEventReconstructor::MakeTrackCandidatesWithTwoSegments(AliMUONSegme
     // pointer to segment
     endSegment = (AliMUONSegment*) ((*fSegmentsPtr[endStation])[iEndSegment]);
     // test compatibility between current segment and "extrapSegment"
+    // 4 because 4 quantities in chi2
     if ((endSegment->
         NormalizedChi2WithSegment(extrapSegment,
                                   fMaxSigma2Distance)) <= 4.0) {
@@ -892,6 +1104,7 @@ Int_t AliMUONEventReconstructor::MakeTrackCandidatesWithOneSegmentAndOnePoint(Al
       // pointer to HitForRec
       hit = (AliMUONHitForRec*) ((*fHitsForRecPtr)[iHit]);
       // test compatibility between current HitForRec and "extrapHitForRec"
+      // 2 because 2 quantities in chi2
       if ((hit->
           NormalizedChi2WithHitForRec(extrapHitForRec,
                                       fMaxSigma2Distance)) <= 2.0) {
@@ -941,7 +1154,7 @@ void AliMUONEventReconstructor::MakeTrackCandidates(void)
       // because candidates with 2 segments have to looked for only once.
       if (begStation == 4)
        nbCan2Seg = MakeTrackCandidatesWithTwoSegments(begSegment);
-      // Look for track candidates with one segments and one point,
+      // Look for track candidates with one segment and one point,
       // "begSegment" and all compatible HitForRec's in other station.
       // Only if "begSegment" does not belong already to a track candidate.
       // Is that a too strong condition ????
@@ -956,51 +1169,77 @@ void AliMUONEventReconstructor::MakeTrackCandidates(void)
 void AliMUONEventReconstructor::FollowTracks(void)
 {
   // Follow tracks in stations(1..) 3, 2 and 1
-  AliMUONHitForRec *bestHit, *extrapHit, *hit;
-  AliMUONSegment *bestSegment, *extrapSegment, *segment;
-  AliMUONTrack *track;
-  AliMUONTrackParam *trackParam1, trackParam[2];
-  Int_t ch, chBestHit, iHit, iSegment, station, trackIndex;
-  Double_t bestChi2, chi2, dZ1, dZ2, maxSigma2Distance, mcsFactor;
-  AliMUON *MUON = (AliMUON*) gAlice->GetModule("MUON"); // necessary ????
-  maxSigma2Distance = 4. * fMaxSigma2Distance; // sigma2cut increased by 4 !!!!
+  // too long: should be made more modular !!!!
+  AliMUONHitForRec *bestHit, *extrapHit, *extrapCorrHit, *hit;
+  AliMUONSegment *bestSegment, *extrapSegment, *extrapCorrSegment, *segment;
+  AliMUONTrack *track, *nextTrack;
+  AliMUONTrackParam *trackParam1, trackParam[2], trackParamVertex;
+  // -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;
   if (fPrintLevel >= 2)
     cout << "enter FollowTracks" << endl;
   // Loop over track candidates
-  for (trackIndex = 0; trackIndex < fNRecTracks; trackIndex++) {
+  track = (AliMUONTrack*) fRecTracksPtr->First();
+  trackIndex = -1;
+  while (track) {
+    // Follow function for each track candidate ????
+    trackIndex++;
+    nextTrack = (AliMUONTrack*) fRecTracksPtr->After(track); // prepare next track
     if (fPrintLevel >= 2)
       cout << "FollowTracks: track candidate(0..): " << trackIndex << endl;
-    // function for each track candidate ????
-    track = (AliMUONTrack*) ((*fRecTracksPtr)[trackIndex]);
-    // Fit track candidate from vertex at X = Y = 0 
-    track->Fit(track->GetTrackParamAtVertex(), 3);
+    // Fit track candidate
+    track->SetFitMCS(0); // without multiple Coulomb scattering
+    track->SetFitNParam(3); // with 3 parameters (X = Y = 0)
+    track->SetFitStart(0); // from parameters at vertex
+    track->Fit();
     if (fPrintLevel >= 10) {
       cout << "FollowTracks: track candidate(0..): " << trackIndex
-          << " after fit in stations(1..) 4 and 5" << endl;
+          << " after fit in stations(0..) 3 and 4" << endl;
       track->RecursiveDump();
     }
     // Loop over stations(1..) 3, 2 and 1
-    // something SPECIAL for stations 2 and 1 for majority coincidence ????
+    // something SPECIAL for stations 2 and 1 for majority 3 coincidence ????
+    // otherwise: majority coincidence 2 !!!!
     for (station = 2; station >= 0; station--) {
       // Track parameters at first track hit (smallest Z)
       trackParam1 = ((AliMUONTrackHit*)
                     (track->GetTrackHitsPtr()->First()))->GetTrackParam();
       // extrapolation to station
       trackParam1->ExtrapToStation(station, trackParam);
-      extrapSegment = new AliMUONSegment::AliMUONSegment(); //  empty segment
+      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();
       mcsFactor        = fChamberThicknessInX0 * mcsFactor * mcsFactor;
       // Z difference from previous station
-      dZ1 = (&(MUON->Chamber(2 * station)))->Z() -
-       (&(MUON->Chamber(2 * station + 2)))->Z();
+      dZ1 = (&(pMUON->Chamber(2 * station)))->Z() -
+       (&(pMUON->Chamber(2 * station + 2)))->Z();
       // Z difference between the two previous stations
-      dZ2 = (&(MUON->Chamber(2 * station + 2)))->Z() -
-       (&(MUON->Chamber(2 * station + 4)))->Z();
-      extrapSegment->SetBendingCoorReso2(fBendingResolution);
-      extrapSegment->SetNonBendingCoorReso2(fNonBendingResolution);
-      extrapSegment->UpdateFromStationTrackParam(trackParam, mcsFactor, dZ1, dZ2);
+      dZ2 = (&(pMUON->Chamber(2 * station + 2)))->Z() -
+       (&(pMUON->Chamber(2 * station + 4)))->Z();
+      // Z difference between the two chambers in the previous station
+      dZ3 = (&(pMUON->Chamber(2 * station)))->Z() -
+       (&(pMUON->Chamber(2 * station + 1)))->Z();
+      extrapSegment->SetBendingCoorReso2(fBendingResolution * fBendingResolution);
+      extrapSegment->
+       SetNonBendingCoorReso2(fNonBendingResolution * fNonBendingResolution);
+      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) {
@@ -1014,7 +1253,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;
@@ -1038,7 +1290,8 @@ void AliMUONEventReconstructor::FollowTracks(void)
        // Look for best compatible HitForRec in station:
        // should consider all possibilities ????
        // multiple scattering ???? do about like for extrapSegment !!!!
-       extrapHit = new AliMUONHitForRec::AliMUONHitForRec(); //  empty hit
+       extrapHit = new AliMUONHitForRec(); //  empty hit
+       extrapCorrHit = new AliMUONHitForRec(); //  empty corrected hit
        bestChi2 = 3.0;
        bestHit = NULL;
        if (fPrintLevel >= 10) {
@@ -1047,33 +1300,56 @@ void AliMUONEventReconstructor::FollowTracks(void)
               << endl;
        }
        // Loop over chambers of the station
-       for (ch = 0; ch < 2; ch++) {
+       for (chInStation = 0; chInStation < 2; chInStation++) {
          // coordinates of extrapolated hit
-         extrapHit->SetBendingCoor((&(trackParam[ch]))->GetBendingCoor());
-         extrapHit->SetNonBendingCoor((&(trackParam[ch]))->GetNonBendingCoor());
+         extrapHit->
+           SetBendingCoor((&(trackParam[chInStation]))->GetBendingCoor());
+         extrapHit->
+           SetNonBendingCoor((&(trackParam[chInStation]))->GetNonBendingCoor());
          // 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];
               iHit < fIndexOfFirstHitForRecPerChamber[ch] +
                 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) {
              // update best Chi2 and HitForRec if better found
              bestHit = hit;
              bestChi2 = chi2;
-             chBestHit = ch;
+             chBestHit = chInStation;
            }
          }
        }
        if (bestHit) {
          // best hit found: add it to track candidate
          track->AddHitForRec(bestHit);
-         // set track parameters at these two TrakHit's
+         // set track parameters at this TrackHit
          track->SetTrackParamAtHit(track->GetNTrackHits() - 1,
                                    &(trackParam[chBestHit]));
          if (fPrintLevel >= 10) {
@@ -1083,30 +1359,459 @@ void AliMUONEventReconstructor::FollowTracks(void)
          }
        }
        else {
-         fRecTracksPtr->RemoveAt(trackIndex); // Remove candidate
+         // 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();
-      // Track fit from first track hit varying X and Y
-      track->Fit(trackParam1, 5);
+      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);
+      // without multiple Coulomb scattering if not all stations
+      else track->SetFitMCS(0);
+      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;
        track->RecursiveDump();
       }
-      delete extrapSegment;
+      // Track extrapolation to the vertex through the absorber (Branson)
+      // after going through the first station
+      if (station == 0) {
+       trackParamVertex = *trackParam1;
+       (&trackParamVertex)->ExtrapToVertex();
+       track->SetTrackParamAtVertex(&trackParamVertex);
+       if (fPrintLevel >= 1) {
+         cout << "FollowTracks: track candidate(0..): " << trackIndex
+              << " after extrapolation to vertex" << endl;
+         track->RecursiveDump();
+       }
+      }
     } // for (station = 2;...
-  } // for (trackIndex = 0;...
+    // go really to next track
+    track = nextTrack;
+  } // while (track)
+  // Compression of track array (necessary after Remove ????)
+  fRecTracksPtr->Compress();
   return;
 }
 
-void AliMUONEventReconstructor::Streamer(TBuffer &R__b)
+  //__________________________________________________________________________
+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)
+{
+  // Dump reconstructed event (track parameters at vertex and at first hit),
+  // and the particle parameters
+
+  AliMUONTrack *track;
+  AliMUONTrackParam *trackParam, *trackParam1;
+  TParticle *p;
+  Double_t bendingSlope, nonBendingSlope, pYZ;
+  Double_t pX, pY, pZ, x, y, z, c;
+  Int_t np, trackIndex, nTrackHits;
+  if (fPrintLevel >= 1) cout << "****** enter EventDump ******" << endl;
+  if (fPrintLevel >= 1) {
+    cout << " Number of Reconstructed tracks :" <<  fNRecTracks << endl; 
+  }
+  fRecTracksPtr->Compress(); // for simple loop without "Next" since no hole
+  // Loop over reconstructed tracks
+  for (trackIndex = 0; trackIndex < fNRecTracks; trackIndex++) {
+    if (fTrackMethod != 1) continue; //AZ - skip the rest for now
+    if (fPrintLevel >= 1)
+      cout << " track number: " << trackIndex << endl;
+    // function for each track for modularity ????
+    track = (AliMUONTrack*) ((*fRecTracksPtr)[trackIndex]);
+    nTrackHits = track->GetNTrackHits();
+    if (fPrintLevel >= 1)
+      cout << " number of track hits: " << nTrackHits << endl;
+    // track parameters at Vertex
+    trackParam = track->GetTrackParamAtVertex();
+    x = trackParam->GetNonBendingCoor();
+    y = trackParam->GetBendingCoor();
+    z = trackParam->GetZ();
+    bendingSlope = trackParam->GetBendingSlope();
+    nonBendingSlope = trackParam->GetNonBendingSlope();
+    pYZ = 1/TMath::Abs(trackParam->GetInverseBendingMomentum());
+    pZ = pYZ/TMath::Sqrt(1+bendingSlope*bendingSlope);
+    pX = pZ * nonBendingSlope;
+    pY = pZ * bendingSlope;
+    c = TMath::Sign(1.0, trackParam->GetInverseBendingMomentum());
+    if (fPrintLevel >= 1)
+      printf(" track parameters at Vertex z= %f: X= %f Y= %f pX= %f pY= %f pZ= %f c= %f\n",
+            z, x, y, pX, pY, pZ, c);
+
+    // track parameters at first hit
+    trackParam1 = ((AliMUONTrackHit*)
+                  (track->GetTrackHitsPtr()->First()))->GetTrackParam();
+    x = trackParam1->GetNonBendingCoor();
+    y = trackParam1->GetBendingCoor();
+    z = trackParam1->GetZ();
+    bendingSlope = trackParam1->GetBendingSlope();
+    nonBendingSlope = trackParam1->GetNonBendingSlope();
+    pYZ = 1/TMath::Abs(trackParam1->GetInverseBendingMomentum());
+    pZ = pYZ/TMath::Sqrt(1.0 + bendingSlope * bendingSlope);
+    pX = pZ * nonBendingSlope;
+    pY = pZ * bendingSlope;
+    c = TMath::Sign(1.0, trackParam1->GetInverseBendingMomentum());
+    if (fPrintLevel >= 1)
+      printf(" track parameters at z= %f: X= %f Y= %f pX= %f pY= %f pZ= %f c= %f\n",
+            z, x, y, pX, pY, pZ, c);
+  }
+  // informations about generated particles
+  np = gAlice->GetNtrack();
+  printf(" **** number of generated particles: %d  \n", np);
+  
+  for (Int_t iPart = 0; iPart < np; 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::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");
+   //AZif (fRecoEvent->MakeDumpTracks(fRecTracksPtr)) {
+   if (fRecoEvent->MakeDumpTracks(fMuons, fRecTracksPtr, this)) { //AZ
+      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();
+}
+
+//__________________________________________________________________________
+void AliMUONEventReconstructor::MakeTrackCandidatesK(void)
+{
+  // To make initial tracks for Kalman filter from the list of segments
+  Int_t istat, iseg;
+  AliMUONSegment *segment;
+  AliMUONTrackK *trackK;
+
+  if (fPrintLevel >= 1) cout << "enter MakeTrackCandidatesK" << endl;
+  // Reset the TClonesArray of reconstructed tracks
+  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;
+
+  AliMUONTrackK a(this, fHitsForRecPtr); // bad idea ???
+  // Loop over stations(1...) 5 and 4
+  for (istat=4; istat>=3; istat--) {
+    // Loop over segments in the station
+    for (iseg=0; iseg<fNSegments[istat]; iseg++) {
+      // Transform segments to tracks and evaluate covariance matrix
+      segment = (AliMUONSegment*) ((*fSegmentsPtr[istat])[iseg]);
+      trackK = new ((*fRecTracksPtr)[fNRecTracks]) AliMUONTrackK(segment);
+      fNRecTracks++;
+    } // for (iseg=0;...)
+  } // for (istat=4;...)
+  return;
+}
+
+//__________________________________________________________________________
+void AliMUONEventReconstructor::FollowTracksK(void)
+{
+  // Follow tracks using Kalman filter
+  Bool_t Ok;
+  Int_t icand, ichamBeg, ichamEnd, chamBits;
+  Double_t zDipole1, zDipole2;
+  AliMUONTrackK *trackK;
+  AliMUONHitForRec *hit;
+  AliMUONRawCluster *clus;
+  TClonesArray *rawclusters;
+  AliMUON *pMUON;
+  clus = 0; rawclusters = 0;
+
+  zDipole1 = GetSimpleBPosition() - GetSimpleBLength()/2;
+  zDipole2 = zDipole1 + GetSimpleBLength();
+
+  // Print hits
+  pMUON  = (AliMUON*) gAlice->GetModule("MUON");
+  for (Int_t i1=0; i1<fNHitsForRec; i1++) {
+    hit = (AliMUONHitForRec*) ((*fHitsForRecPtr)[i1]);
+    //if (hit->GetTHTrack() > 1 || hit->GetGeantSignal() == 0) continue;
+    /*
+    cout << " Hit #" << hit->GetChamberNumber() << " ";
+    cout << hit->GetBendingCoor() << " ";
+    cout << hit->GetNonBendingCoor() << " ";
+    cout << hit->GetZ() << " ";
+    cout << hit->GetGeantSignal() << " ";
+    cout << hit->GetTHTrack() << endl;
+    */
+    /*
+    printf(" Hit # %d %10.4f %10.4f %10.4f",
+           hit->GetChamberNumber(), hit->GetBendingCoor(),
+           hit->GetNonBendingCoor(), hit->GetZ());
+    if (fRecGeantHits) {
+      // from GEANT hits
+      printf(" %3d %3d \n", hit->GetGeantSignal(), hit->GetTHTrack());
+    } else {
+      // from raw clusters
+      rawclusters = pMUON->RawClustAddress(hit->GetChamberNumber());
+      clus = (AliMUONRawCluster*) rawclusters->UncheckedAt(hit->
+                                               GetHitNumber());
+      printf("%3d", clus->fTracks[1]-1);
+      if (clus->fTracks[2] != 0) printf("%3d \n", clus->fTracks[2]-1);
+      else printf("\n");
+    }
+    */
+  }
+
+  icand = -1;
+  Int_t nSeeds = fNRecTracks; // starting number of seeds
+  // Loop over track candidates
+  while (icand < fNRecTracks-1) {
+    icand ++;
+    trackK = (AliMUONTrackK*) ((*fRecTracksPtr)[icand]);
+
+    // Discard candidate which will produce the double track
+    if (icand > 0) {
+      Ok = CheckCandidateK(icand,nSeeds);
+      if (!Ok) {
+        //trackK->SetRecover(-1); // mark candidate to be removed
+        //continue;
+      }
+    }
+
+    Ok = kTRUE;
+    if (trackK->GetRecover() == 0) hit = (AliMUONHitForRec*) 
+                                   trackK->GetHitOnTrack()->Last(); // last hit
+    else hit = (AliMUONHitForRec*) (*trackK->GetHitOnTrack())[1]; // 2'nd hit
+    ichamBeg = hit->GetChamberNumber();
+    ichamEnd = 0;
+    // Check propagation direction
+    if (trackK->GetTrackDir() > 0) {
+      ichamEnd = 9; // forward propagation
+      Ok = trackK->KalmanFilter(ichamBeg,ichamEnd,kFALSE,zDipole1,zDipole2);
+      if (Ok) {
+        ichamBeg = ichamEnd;
+        ichamEnd = 6; // backward propagation
+       // Change weight matrix and zero fChi2 for backpropagation
+        trackK->StartBack();
+        Ok = trackK->KalmanFilter(ichamBeg,ichamEnd,kTRUE,zDipole1,zDipole2);
+        ichamBeg = ichamEnd;
+        ichamEnd = 0;
+      }
+    } else {
+      if (trackK->GetBPFlag()) {
+       // backpropagation
+        ichamEnd = 6; // backward propagation
+       // Change weight matrix and zero fChi2 for backpropagation
+        trackK->StartBack();
+        Ok = trackK->KalmanFilter(ichamBeg,ichamEnd,kTRUE,zDipole1,zDipole2);
+        ichamBeg = ichamEnd;
+        ichamEnd = 0;
+      }
+    }
+
+    if (Ok) {
+      trackK->SetTrackDir(-1);
+      trackK->SetBPFlag(kFALSE);
+      Ok = trackK->KalmanFilter(ichamBeg,ichamEnd,kFALSE,zDipole1,zDipole2);
+    }
+    if (Ok) trackK->SetTrackQuality(0); // compute "track quality"
+    else trackK->SetRecover(-1); // mark candidate to be removed
+
+    // Majority 3 of 4 in first 2 stations
+    chamBits = 0;
+    for (Int_t i=0; i<trackK->GetNTrackHits(); i++) {
+      hit = (AliMUONHitForRec*) (*trackK->GetHitOnTrack())[i];
+      chamBits |= BIT(hit->GetChamberNumber()-1);
+    }
+    //if (!((chamBits&3)==3 || (chamBits>>2&3)==3)) trackK->SetRecover(-1); 
+                                 //mark candidate to be removed
+  } // while
+
+  for (Int_t i=0; i<fNRecTracks; i++) {
+    trackK = (AliMUONTrackK*) ((*fRecTracksPtr)[i]);
+    if (trackK->GetRecover() < 0) fRecTracksPtr->RemoveAt(i);
+  }
+
+  // Compress TClonesArray
+  fRecTracksPtr->Compress();
+  fNRecTracks = fRecTracksPtr->GetEntriesFast();
+  return;
+}
+
+//__________________________________________________________________________
+Bool_t AliMUONEventReconstructor::CheckCandidateK(Int_t icand, Int_t nSeeds)
+{
+  // Discards track candidate if it will produce the double track (having
+  // the same seed segment hits as hits of a good track found before)
+  AliMUONTrackK *track1, *track2;
+  AliMUONHitForRec *hit1, *hit2, *hit;
+
+  track1 = (AliMUONTrackK*) ((*fRecTracksPtr)[icand]);
+  hit1 = (AliMUONHitForRec*) (*track1->GetHitOnTrack())[0]; // 1'st hit
+  hit2 = (AliMUONHitForRec*) (*track1->GetHitOnTrack())[1]; // 2'nd hit
+
+  for (Int_t i=0; i<icand; i++) {
+    track2 = (AliMUONTrackK*) ((*fRecTracksPtr)[i]);
+    //if (track2->GetRecover() < 0) continue;
+    if (track2->GetRecover() < 0 && icand >= nSeeds) continue;
+
+    if (track1->GetStartSegment() == track2->GetStartSegment()) {
+      return kFALSE;
+    } else {
+      Int_t nSame = 0;
+      for (Int_t j=0; j<track2->GetNTrackHits(); j++) {
+        hit = (AliMUONHitForRec*) (*track2->GetHitOnTrack())[j];
+        if (hit == hit1 || hit == hit2) {
+          nSame++;
+          if (nSame == 2) return kFALSE;
+        }
+      } // for (Int_t j=0;
+    }
+  } // for (Int_t i=0;
+  return kTRUE;
+}
+
+//__________________________________________________________________________
+void AliMUONEventReconstructor::RemoveDoubleTracksK(void)
+{
+  // Removes double tracks (sharing more than half of their hits). Keeps
+  // the track with higher quality
+  AliMUONTrackK *track1, *track2, *trackToKill;
+
+  // Sort tracks according to their quality
+  fRecTracksPtr->Sort();
+
+  // Loop over first track of the pair
+  track1 = (AliMUONTrackK*) fRecTracksPtr->First();
+  while (track1) {
+    // Loop over second track of the pair
+    track2 = (AliMUONTrackK*) fRecTracksPtr->After(track1);
+    while (track2) {
+      // Check whether or not to keep track2
+      if (!track2->KeepTrack(track1)) {
+        cout << " Killed track: " << 1/(*track2->GetTrackParameters())(4,0) <<
+         " " << track2->GetTrackQuality() << endl;
+        trackToKill = track2;
+        track2 = (AliMUONTrackK*) fRecTracksPtr->After(track2);
+        trackToKill->Kill();
+        fRecTracksPtr->Compress();
+      } else track2 = (AliMUONTrackK*) fRecTracksPtr->After(track2);
+    } // track2
+    track1 = (AliMUONTrackK*) fRecTracksPtr->After(track1);
+  } // track1
+
+  fNRecTracks = fRecTracksPtr->GetEntriesFast();
+  cout << " Number of Kalman tracks: " << fNRecTracks << endl;
+}
+
+//__________________________________________________________________________
+void AliMUONEventReconstructor::GoToVertex(void)
+{
+  // Propagates track to the vertex thru absorber
+  // (using Branson correction for now)
+
+  Double_t zVertex;
+  zVertex = 0;
+  for (Int_t i=0; i<fNRecTracks; i++) {
+    //((AliMUONTrackK*)(*fRecTracksPtr)[i])->Branson();
+    //((AliMUONTrackK*)(*fRecTracksPtr)[i])->GoToZ(zVertex); // w/out absorber
+    ((AliMUONTrackK*)(*fRecTracksPtr)[i])->SetTrackQuality(1); // compute Chi2
+    ((AliMUONTrackK*)(*fRecTracksPtr)[i])->GoToVertex(); // with absorber
+  }
 }