]> git.uio.no Git - u/mrichter/AliRoot.git/blobdiff - ITS/AliITStrackerMI.cxx
Fixes for Coverity warnings
[u/mrichter/AliRoot.git] / ITS / AliITStrackerMI.cxx
index 91f0e9529d5311738f353704be48e40a032a23f4..72031256b6f87ffd3498507e5f9126f9fcbbf6eb 100644 (file)
@@ -19,6 +19,8 @@
 //    It reads AliITSRecPoint clusters and creates AliITStrackMI tracks
 //                   and fills with them the ESD
 //          Origin: Marian Ivanov, CERN, Marian.Ivanov@cern.ch 
+//          Current support and development: 
+//                     Andrea Dainese, andrea.dainese@lnl.infn.it
 //     dE/dx analysis by: Boris Batyunya, JINR, Boris.Batiounia@cern.ch
 //     Params moved to AliITSRecoParam by: Andrea Dainese, INFN
 //     Material budget from TGeo by: Ludovic Gaudichet & Andrea Dainese, INFN
 
 #include <TMatrixD.h>
 #include <TTree.h>
-#include <TTreeStream.h>
 #include <TDatabasePDG.h>
 #include <TString.h>
 #include <TRandom.h>
+#include <TTreeStream.h>
+#include <TVector3.h>
 
-
+#include "AliLog.h"
+#include "AliGeomManager.h"
+#include "AliITSPlaneEff.h"
+#include "AliTrackPointArray.h"
 #include "AliESDEvent.h"
 #include "AliESDtrack.h"
-#include "AliESDVertex.h"
 #include "AliV0.h"
-#include "AliHelix.h"
+#include "AliITSChannelStatus.h"
+#include "AliITSDetTypeRec.h"
 #include "AliITSRecPoint.h"
+#include "AliITSRecPointContainer.h"
 #include "AliITSgeomTGeo.h"
-#include "AliITStrackerMI.h"
 #include "AliITSReconstructor.h"
-#include "AliTrackPointArray.h"
-#include "AliAlignObj.h"
 #include "AliITSClusterParam.h"
+#include "AliITSsegmentation.h"
+#include "AliITSCalibration.h"
+#include "AliITSPlaneEffSPD.h"
+#include "AliITSPlaneEffSDD.h"
+#include "AliITSPlaneEffSSD.h"
+#include "AliITSV0Finder.h"
+#include "AliITStrackerMI.h"
+#include "AliMathBase.h"
 
 ClassImp(AliITStrackerMI)
 
@@ -63,7 +75,7 @@ fLastLayerToTrackTo(0),
 fCoefficients(0),
 fEsd(0),
 fTrackingPhase("Default"),
-fUseTGeo(0),
+fUseTGeo(3),
 fNtracks(0),
 fxOverX0Pipe(-1.),
 fxTimesRhoPipe(-1.),
@@ -73,12 +85,23 @@ fxOverX0ShieldTrks(0),
 fxTimesRhoShieldTrks(0),
 fxOverX0LayerTrks(0),
 fxTimesRhoLayerTrks(0),
-fDebugStreamer(0){
+fDebugStreamer(0),
+fITSChannelStatus(0),
+fkDetTypeRec(0),
+fPlaneEff(0) {
   //Default constructor
   Int_t i;
   for(i=0;i<4;i++) fSPDdetzcentre[i]=0.;
-  for(i=0;i<2;i++) {fxOverX0Shield[i]=-1.;fxTimesRhoShield[i]=-1.;}
+  for(i=0;i<2;i++) {
+    fxOverX0Shield[i]=-1.;
+    fxTimesRhoShield[i]=-1.;
+    fConstraint[i]=0;
+  }
   for(i=0;i<6;i++) {fxOverX0Layer[i]=-1.;fxTimesRhoLayer[i]=-1.;}
+  fOriginal.SetOwner();
+  for(i=0;i<AliITSgeomTGeo::kNLayers;i++)fForceSkippingOfLayer[i]=0;
+  for(i=0;i<100000;i++)fBestTrackIndex[i]=0;
+
 }
 //------------------------------------------------------------------------
 AliITStrackerMI::AliITStrackerMI(const Char_t *geom) : AliTracker(),
@@ -95,7 +118,7 @@ fLastLayerToTrackTo(AliITSRecoParam::GetLastLayerToTrackTo()),
 fCoefficients(0),
 fEsd(0),
 fTrackingPhase("Default"),
-fUseTGeo(0),
+fUseTGeo(3),
 fNtracks(0),
 fxOverX0Pipe(-1.),
 fxTimesRhoPipe(-1.),
@@ -105,7 +128,10 @@ fxOverX0ShieldTrks(0),
 fxTimesRhoShieldTrks(0),
 fxOverX0LayerTrks(0),
 fxTimesRhoLayerTrks(0),
-fDebugStreamer(0){
+fDebugStreamer(0),
+fITSChannelStatus(0),
+fkDetTypeRec(0),
+fPlaneEff(0) {
   //--------------------------------------------------------------------
   //This is the AliITStrackerMI constructor
   //--------------------------------------------------------------------
@@ -113,6 +139,7 @@ fDebugStreamer(0){
     AliWarning("\"geom\" is actually a dummy argument !");
   }
 
+  fOriginal.SetOwner();
   fCoefficients = 0;
   fAfterV0     = kFALSE;
 
@@ -121,9 +148,11 @@ fDebugStreamer(0){
     Int_t ndet=AliITSgeomTGeo::GetNDetectors(i);
 
     Double_t xyz[3], &x=xyz[0], &y=xyz[1], &z=xyz[2];
-    AliITSgeomTGeo::GetOrigTranslation(i,1,1,xyz); 
+    AliITSgeomTGeo::GetTranslation(i,1,1,xyz); 
     Double_t poff=TMath::ATan2(y,x);
     Double_t zoff=z;
+
+    AliITSgeomTGeo::GetOrigTranslation(i,1,1,xyz);
     Double_t r=TMath::Sqrt(x*x + y*y);
 
     AliITSgeomTGeo::GetOrigTranslation(i,1,2,xyz);
@@ -141,9 +170,10 @@ fDebugStreamer(0){
         TGeoHMatrix m; AliITSgeomTGeo::GetOrigMatrix(i,j,k,m);
         const TGeoHMatrix *tm=AliITSgeomTGeo::GetTracking2LocalMatrix(i,j,k);
         m.Multiply(tm);
-        Double_t txyz[3]={0.}, xyz[3]={0.};
+        Double_t txyz[3]={0.};
+       xyz[0]=0.;xyz[1]=0.;xyz[2]=0.;
         m.LocalToMaster(txyz,xyz);
-        Double_t r=TMath::Sqrt(xyz[0]*xyz[0] + xyz[1]*xyz[1]);
+        r=TMath::Sqrt(xyz[0]*xyz[0] + xyz[1]*xyz[1]);
         Double_t phi=TMath::ATan2(xyz[1],xyz[0]);
 
         if (phi<0) phi+=TMath::TwoPi();
@@ -151,10 +181,19 @@ fDebugStreamer(0){
 
         AliITSdetector &det=fgLayers[i-1].GetDetector((j-1)*ndet + k-1); 
         new(&det) AliITSdetector(r,phi); 
-      } 
-    }  
+       // compute the real radius (with misalignment)
+        TGeoHMatrix mmisal(*(AliITSgeomTGeo::GetMatrix(i,j,k)));
+        mmisal.Multiply(tm);
+       xyz[0]=0.;xyz[1]=0.;xyz[2]=0.;
+        mmisal.LocalToMaster(txyz,xyz);
+        Double_t rmisal=TMath::Sqrt(xyz[0]*xyz[0] + xyz[1]*xyz[1]);
+       det.SetRmisal(rmisal);
+       
+      } // end loop on detectors
+    } // end loop on ladders
+    fForceSkippingOfLayer[i-1] = 0;
+  } // end loop on layers
 
-  }
 
   fI=AliITSgeomTGeo::GetNLayers();
 
@@ -169,31 +208,62 @@ fDebugStreamer(0){
                     AliITSReconstructor::GetRecoParam()->GetSigmaZVdef()}; 
   SetVertex(xyzVtx,ersVtx);
 
-  for (Int_t i=0; i<AliITSgeomTGeo::GetNLayers(); i++) fLayersNotToSkip[i]=AliITSRecoParam::GetLayersNotToSkip(i);
   fLastLayerToTrackTo=AliITSRecoParam::GetLastLayerToTrackTo();
   for (Int_t i=0;i<100000;i++){
     fBestTrackIndex[i]=0;
   }
 
   // store positions of centre of SPD modules (in z)
+  //  The convetion is that fSPDdetzcentre is ordered from -z to +z
   Double_t tr[3];
   AliITSgeomTGeo::GetTranslation(1,1,1,tr);
-  fSPDdetzcentre[0] = tr[2];
-  AliITSgeomTGeo::GetTranslation(1,1,2,tr);
-  fSPDdetzcentre[1] = tr[2];
-  AliITSgeomTGeo::GetTranslation(1,1,3,tr);
-  fSPDdetzcentre[2] = tr[2];
-  AliITSgeomTGeo::GetTranslation(1,1,4,tr);
-  fSPDdetzcentre[3] = tr[2];
+  if (tr[2]<0) { // old geom (up to v5asymmPPR)
+    AliITSgeomTGeo::GetTranslation(1,1,1,tr);
+    fSPDdetzcentre[0] = tr[2];
+    AliITSgeomTGeo::GetTranslation(1,1,2,tr);
+    fSPDdetzcentre[1] = tr[2];
+    AliITSgeomTGeo::GetTranslation(1,1,3,tr);
+    fSPDdetzcentre[2] = tr[2];
+    AliITSgeomTGeo::GetTranslation(1,1,4,tr);
+    fSPDdetzcentre[3] = tr[2];
+  } else { // new geom (from v11Hybrid)
+    AliITSgeomTGeo::GetTranslation(1,1,4,tr);
+    fSPDdetzcentre[0] = tr[2];
+    AliITSgeomTGeo::GetTranslation(1,1,3,tr);
+    fSPDdetzcentre[1] = tr[2];
+    AliITSgeomTGeo::GetTranslation(1,1,2,tr);
+    fSPDdetzcentre[2] = tr[2];
+    AliITSgeomTGeo::GetTranslation(1,1,1,tr);
+    fSPDdetzcentre[3] = tr[2];
+  }
 
   fUseTGeo = AliITSReconstructor::GetRecoParam()->GetUseTGeoInTracker();
+  if(AliITSReconstructor::GetRecoParam()->GetExtendedEtaAcceptance() && fUseTGeo!=1 && fUseTGeo!=3) {
+    AliWarning("fUseTGeo changed to 3 because fExtendedEtaAcceptance is kTRUE");
+    fUseTGeo = 3;
+  }
 
   for(Int_t i=0;i<2;i++) {fxOverX0Shield[i]=-1.;fxTimesRhoShield[i]=-1.;}
   for(Int_t i=0;i<6;i++) {fxOverX0Layer[i]=-1.;fxTimesRhoLayer[i]=-1.;}
   
-  fDebugStreamer = new TTreeSRedirector("ITSdebug.root");
-
+  if (AliITSReconstructor::GetRecoParam()->GetESDV0Params()->StreamLevel()>0)
+    fDebugStreamer = new TTreeSRedirector("ITSdebug.root");
+
+  // only for plane efficiency evaluation
+  if (AliITSReconstructor::GetRecoParam()->GetComputePlaneEff() &&
+      AliITSReconstructor::GetRecoParam()->GetIPlanePlaneEff()>=0) {
+    Int_t iplane=AliITSReconstructor::GetRecoParam()->GetIPlanePlaneEff();
+    if(!AliITSReconstructor::GetRecoParam()->GetLayersToSkip(iplane)==1)
+      AliWarning(Form("Evaluation of Plane Eff for layer %d will be attempted without removing it from tracker",iplane));
+    if (iplane<2) fPlaneEff = new AliITSPlaneEffSPD();
+    else if (iplane<4) fPlaneEff = new AliITSPlaneEffSDD();
+    else fPlaneEff = new AliITSPlaneEffSSD();
+    if(AliITSReconstructor::GetRecoParam()->GetReadPlaneEffFromOCDB())
+       if(!fPlaneEff->ReadFromCDB()) {AliWarning("AliITStrackerMI reading of AliITSPlaneEff from OCDB failed") ;}
+    if(AliITSReconstructor::GetRecoParam()->GetHistoPlaneEff()) fPlaneEff->SetCreateHistos(kTRUE);
+  }
 }
+/*
 //------------------------------------------------------------------------
 AliITStrackerMI::AliITStrackerMI(const AliITStrackerMI &tracker):AliTracker(tracker),
 fI(tracker.fI),
@@ -219,8 +289,12 @@ fxOverX0ShieldTrks(0),
 fxTimesRhoShieldTrks(0),
 fxOverX0LayerTrks(0),
 fxTimesRhoLayerTrks(0),
-fDebugStreamer(tracker.fDebugStreamer){
+fDebugStreamer(tracker.fDebugStreamer),
+fITSChannelStatus(tracker.fITSChannelStatus),
+fkDetTypeRec(tracker.fkDetTypeRec),
+fPlaneEff(tracker.fPlaneEff) {
   //Copy constructor
+  fOriginal.SetOwner();
   Int_t i;
   for(i=0;i<4;i++) {
     fSPDdetzcentre[i]=tracker.fSPDdetzcentre[i];
@@ -234,6 +308,7 @@ fDebugStreamer(tracker.fDebugStreamer){
     fxTimesRhoShield[i]=tracker.fxTimesRhoShield[i];
   }
 }
+
 //------------------------------------------------------------------------
 AliITStrackerMI & AliITStrackerMI::operator=(const AliITStrackerMI &tracker){
   //Assignment operator
@@ -241,6 +316,7 @@ AliITStrackerMI & AliITStrackerMI::operator=(const AliITStrackerMI &tracker){
   new(this) AliITStrackerMI(tracker);
   return *this;
 }
+*/
 //------------------------------------------------------------------------
 AliITStrackerMI::~AliITStrackerMI()
 {
@@ -253,35 +329,67 @@ AliITStrackerMI::~AliITStrackerMI()
     //fDebugStreamer->Close();
     delete fDebugStreamer;
   }
+  if(fITSChannelStatus) delete fITSChannelStatus;
+  if(fPlaneEff) delete fPlaneEff;
 }
 //------------------------------------------------------------------------
-void AliITStrackerMI::SetLayersNotToSkip(Int_t *l) {
+void AliITStrackerMI::ReadBadFromDetTypeRec() {
   //--------------------------------------------------------------------
-  //This function set masks of the layers which must be not skipped
+  //This function read ITS bad detectors, chips, channels from AliITSDetTypeRec
+  //i.e. from OCDB
   //--------------------------------------------------------------------
-  for (Int_t i=0; i<AliITSgeomTGeo::GetNLayers(); i++) fLayersNotToSkip[i]=l[i];
+
+  if(!AliITSReconstructor::GetRecoParam()->GetUseBadZonesFromOCDB()) return;
+
+  Info("ReadBadFromDetTypeRec","Reading info about bad ITS detectors and channels");
+
+  if(!fkDetTypeRec) Error("ReadBadFromDetTypeRec","AliITSDetTypeRec nof found!\n");
+
+  // ITS channels map
+  if(fITSChannelStatus) delete fITSChannelStatus;
+  fITSChannelStatus = new AliITSChannelStatus(fkDetTypeRec);
+
+  // ITS detectors and chips
+  Int_t i=0,j=0,k=0,ndet=0;
+  for (i=1; i<AliITSgeomTGeo::GetNLayers()+1; i++) {
+    Int_t nBadDetsPerLayer=0;
+    ndet=AliITSgeomTGeo::GetNDetectors(i);    
+    for (j=1; j<AliITSgeomTGeo::GetNLadders(i)+1; j++) {
+      for (k=1; k<ndet+1; k++) {
+        AliITSdetector &det=fgLayers[i-1].GetDetector((j-1)*ndet + k-1);  
+       det.ReadBadDetectorAndChips(i-1,(j-1)*ndet + k-1,fkDetTypeRec);
+       if(det.IsBad()) {nBadDetsPerLayer++;}
+      } // end loop on detectors
+    } // end loop on ladders
+    AliInfo(Form("Layer %d: %d bad out of %d",i-1,nBadDetsPerLayer,ndet*AliITSgeomTGeo::GetNLadders(i)));
+  } // end loop on layers
+  
+  return;
 }
 //------------------------------------------------------------------------
 Int_t AliITStrackerMI::LoadClusters(TTree *cTree) {
   //--------------------------------------------------------------------
   //This function loads ITS clusters
   //--------------------------------------------------------------------
-  TBranch *branch=cTree->GetBranch("ITSRecPoints");
-  if (!branch) { 
-    Error("LoadClusters"," can't get the branch !\n");
-    return 1;
-  }
-
-  TClonesArray dummy("AliITSRecPoint",10000), *clusters=&dummy;
-  branch->SetAddress(&clusters);
+  TClonesArray *clusters = NULL;
+  AliITSRecPointContainer* rpcont=AliITSRecPointContainer::Instance();
+  clusters=rpcont->FetchClusters(0,cTree);
+  if(!clusters) return 1;
 
-  Int_t j=0;
+  if(!(rpcont->IsSPDActive() || rpcont->IsSDDActive() || rpcont->IsSSDActive())){
+      AliError("ITS is not in a known running configuration: SPD, SDD and SSD are not active");
+      return 1;
+  }
+  Int_t i=0,j=0,ndet=0;
   Int_t detector=0;
-  for (Int_t i=0; i<AliITSgeomTGeo::GetNLayers(); i++) {
-    Int_t ndet=fgLayers[i].GetNdetectors();
+  for (i=0; i<AliITSgeomTGeo::GetNLayers(); i++) {
+    ndet=fgLayers[i].GetNdetectors();
     Int_t jmax = j + fgLayers[i].GetNladders()*ndet;
     for (; j<jmax; j++) {           
-      if (!cTree->GetEvent(j)) continue;
+      //      if (!cTree->GetEvent(j)) continue;
+      clusters = rpcont->UncheckedGetClusters(j);
+      if(!clusters)continue;
       Int_t ncl=clusters->GetEntriesFast();
       SignDeltas(clusters,GetZ());
  
@@ -290,22 +398,28 @@ Int_t AliITStrackerMI::LoadClusters(TTree *cTree) {
         detector=c->GetDetectorIndex();
 
        if (!c->Misalign()) AliWarning("Can't misalign this cluster !");
-
-        fgLayers[i].InsertCluster(new AliITSRecPoint(*c));
+       
+       Int_t retval = fgLayers[i].InsertCluster(new AliITSRecPoint(*c));
+       if(retval) {
+         AliWarning(Form("Too many clusters on layer %d!",i));
+         break;  
+       } 
       }
-      clusters->Delete();
+
       // add dead zone "virtual" cluster in SPD, if there is a cluster within 
       // zwindow cm from the dead zone      
+      //  This method assumes that fSPDdetzcentre is ordered from -z to +z
       if (i<2 && AliITSReconstructor::GetRecoParam()->GetAddVirtualClustersInDeadZone()) {
        for (Float_t xdead = 0; xdead < AliITSRecoParam::GetSPDdetxlength(); xdead += (i+1.)*AliITSReconstructor::GetRecoParam()->GetXPassDeadZoneHits()) {
          Int_t lab[4]   = {0,0,0,detector};
          Int_t info[3]  = {0,0,i};
-         Float_t q      = 0.;
-         Float_t hit[5] = {xdead,
+         Float_t q      = 0.; // this identifies virtual clusters
+         Float_t hit[6] = {xdead,
                            0.,
                            AliITSReconstructor::GetRecoParam()->GetSigmaXDeadZoneHit2(),
                            AliITSReconstructor::GetRecoParam()->GetSigmaZDeadZoneHit2(),
-                           q};
+                           q,
+                           0.};
          Bool_t local   = kTRUE;
          Double_t zwindow = AliITSReconstructor::GetRecoParam()->GetZWindowDeadZone();
          hit[1] = fSPDdetzcentre[0]+0.5*AliITSRecoParam::GetSPDdetzlength();
@@ -327,7 +441,7 @@ Int_t AliITStrackerMI::LoadClusters(TTree *cTree) {
          if (TMath::Abs(fgLayers[i].GetDetector(detector).GetZmax()-hit[1])<zwindow) 
            fgLayers[i].InsertCluster(new AliITSRecPoint(lab,hit,info,local));
        }
-      }
+      } // "virtual" clusters in SPD
       
     }
     //
@@ -335,6 +449,9 @@ Int_t AliITStrackerMI::LoadClusters(TTree *cTree) {
     fgLayers[i].SortClusters();
   }
 
+  // check whether we have to skip some layers
+  SetForceSkippingOfLayer();
+
   return 0;
 }
 //------------------------------------------------------------------------
@@ -345,7 +462,25 @@ void AliITStrackerMI::UnloadClusters() {
   for (Int_t i=0; i<AliITSgeomTGeo::GetNLayers(); i++) fgLayers[i].ResetClusters();
 }
 //------------------------------------------------------------------------
-static Int_t CorrectForTPCtoITSDeadZoneMaterial(AliITStrackMI *t) {
+void AliITStrackerMI::FillClusterArray(TObjArray* array) const {
+  //--------------------------------------------------------------------
+  // Publishes all pointers to clusters known to the tracker into the
+  // passed object array.
+  // The ownership is not transfered - the caller is not expected to delete
+  // the clusters.
+  //--------------------------------------------------------------------
+
+  for(Int_t i=0; i<AliITSgeomTGeo::GetNLayers(); i++) {
+    for(Int_t icl=0; icl<fgLayers[i].GetNumberOfClusters(); icl++) {
+      AliCluster *cl = (AliCluster*)fgLayers[i].GetCluster(icl);
+      array->AddLast(cl);
+    }
+  }
+
+  return;
+}
+//------------------------------------------------------------------------
+Int_t AliITStrackerMI::CorrectForTPCtoITSDeadZoneMaterial(AliITStrackMI *t) {
   //--------------------------------------------------------------------
   // Correction for the material between the TPC and the ITS
   //--------------------------------------------------------------------
@@ -358,7 +493,7 @@ static Int_t CorrectForTPCtoITSDeadZoneMaterial(AliITStrackMI *t) {
       if (!t->PropagateToTGeo(AliITSRecoParam::Getrcd(),1))       return 0;// TPC central drum
       if (!t->PropagateToTGeo(AliITSRecoParam::Getriw()+0.001,1)) return 0;// TPC inner wall
   } else {
-    Error("CorrectForTPCtoITSDeadZoneMaterial","Track is already in the dead zone !");
+    printf("CorrectForTPCtoITSDeadZoneMaterial: Track is already in the dead zone !\n");
     return 0;
   }
   
@@ -370,6 +505,9 @@ Int_t AliITStrackerMI::Clusters2Tracks(AliESDEvent *event) {
   // This functions reconstructs ITS tracks
   // The clusters must be already loaded !
   //--------------------------------------------------------------------
+
+  AliDebug(2,Form("SKIPPING %d %d %d %d %d %d",ForceSkippingOfLayer(0),ForceSkippingOfLayer(1),ForceSkippingOfLayer(2),ForceSkippingOfLayer(3),ForceSkippingOfLayer(4),ForceSkippingOfLayer(5)));
+
   fTrackingPhase="Clusters2Tracks";
 
   TObjArray itsTracks(15000);
@@ -386,28 +524,26 @@ Int_t AliITStrackerMI::Clusters2Tracks(AliESDEvent *event) {
     }
   }
   // temporary
-
+  Int_t noesd = 0;
   {/* Read ESD tracks */
     Double_t pimass = TDatabasePDG::Instance()->GetParticle(211)->Mass();
     Int_t nentr=event->GetNumberOfTracks();
-    Info("Clusters2Tracks", "Number of ESD tracks: %d\n", nentr);
+    noesd=nentr;
+    //    Info("Clusters2Tracks", "Number of ESD tracks: %d\n", nentr);
     while (nentr--) {
       AliESDtrack *esd=event->GetTrack(nentr);
+      //  ---- for debugging:
+      //if(TMath::Abs(esd->GetX()-83.65)<0.1) { FILE *f=fopen("tpc.dat","a"); fprintf(f,"%f %f %f %f %f %f\n",(Float_t)event->GetEventNumberInFile(),(Float_t)TMath::Abs(esd->GetLabel()),(Float_t)esd->GetX(),(Float_t)esd->GetY(),(Float_t)esd->GetZ(),(Float_t)esd->Pt()); fclose(f); }
 
       if ((esd->GetStatus()&AliESDtrack::kTPCin)==0) continue;
       if (esd->GetStatus()&AliESDtrack::kTPCout) continue;
       if (esd->GetStatus()&AliESDtrack::kITSin) continue;
       if (esd->GetKinkIndex(0)>0) continue;   //kink daughter
-      AliITStrackMI *t=0;
-      try {
-        t=new AliITStrackMI(*esd);
-      } catch (const Char_t *msg) {
-        //Warning("Clusters2Tracks",msg);
-        delete t;
-        continue;
-      }
+      AliITStrackMI *t = new AliITStrackMI(*esd);
       t->GetDZ(GetX(),GetY(),GetZ(),t->GetDP());              //I.B.
       Double_t vdist = TMath::Sqrt(t->GetD(0)*t->GetD(0)+t->GetD(1)*t->GetD(1));
+
+
       // look at the ESD mass hypothesys !
       if (t->GetMass()<0.9*pimass) t->SetMass(pimass); 
       // write expected q
@@ -445,15 +581,15 @@ Int_t AliITStrackerMI::Clusters2Tracks(AliESDEvent *event) {
   fTrackHypothesys.Expand(nentr);
   fBestHypothesys.Expand(nentr);
   MakeCoefficients(nentr);
-  if(fUseTGeo==3 || fUseTGeo==4) MakeTrksMaterialLUT(nentr);
+  if(fUseTGeo==3 || fUseTGeo==4) MakeTrksMaterialLUT(event->GetNumberOfTracks());
   Int_t ntrk=0;
   // THE TWO TRACKING PASSES
   for (fPass=0; fPass<2; fPass++) {
      Int_t &constraint=fConstraint[fPass]; if (constraint<0) continue;
      for (fCurrentEsdTrack=0; fCurrentEsdTrack<nentr; fCurrentEsdTrack++) {
-       //cerr<<fPass<<"    "<<fCurrentEsdTrack<<'\n';
        AliITStrackMI *t=(AliITStrackMI*)itsTracks.UncheckedAt(fCurrentEsdTrack);
        if (t==0) continue;              //this track has been already tracked
+       //cout<<"========== "<<fPass<<"    "<<fCurrentEsdTrack<<" =========\n";
        if (t->GetReconstructed()&&(t->GetNUsed()<1.5)) continue;  //this track was  already  "succesfully" reconstructed
        Float_t dz[2]; t->GetDZ(GetX(),GetY(),GetZ(),dz);              //I.B.
        if (fConstraint[fPass]) { 
@@ -462,14 +598,17 @@ Int_t AliITStrackerMI::Clusters2Tracks(AliESDEvent *event) {
        }
 
        Int_t tpcLabel=t->GetLabel(); //save the TPC track label       
+       AliDebug(2,Form("LABEL %d pass %d",tpcLabel,fPass));
        fI = 6;
        ResetTrackToFollow(*t);
        ResetBestTrack();
+
        FollowProlongationTree(t,fCurrentEsdTrack,fConstraint[fPass]);
 
        SortTrackHypothesys(fCurrentEsdTrack,20,0);  //MI change
        //
-       AliITStrackMI * besttrack = GetBestHypothesys(fCurrentEsdTrack,t,15);
+       AliITStrackMI *besttrack = GetBestHypothesys(fCurrentEsdTrack,t,15);
        if (!besttrack) continue;
        besttrack->SetLabel(tpcLabel);
        //       besttrack->CookdEdx();
@@ -481,18 +620,17 @@ Int_t AliITStrackerMI::Clusters2Tracks(AliESDEvent *event) {
        if (fConstraint[fPass]&&(!besttrack->IsGoldPrimary())) continue;  //to be tracked also without vertex constrain 
 
        t->SetReconstructed(kTRUE);
-       ntrk++;                     
+       ntrk++;  
+       AliDebug(2,Form("TRACK! (label %d) ncls %d",besttrack->GetLabel(),besttrack->GetNumberOfClusters()));
      }
      GetBestHypothesysMIP(itsTracks); 
   } // end loop on the two tracking passes
 
-  //GetBestHypothesysMIP(itsTracks);
-  if(event->GetNumberOfV0s()>0) UpdateTPCV0(event);
-  if(AliITSReconstructor::GetRecoParam()->GetFindV0s()) FindV02(event);
+  if(event->GetNumberOfV0s()>0) AliITSV0Finder::UpdateTPCV0(event,this);
+  if(AliITSReconstructor::GetRecoParam()->GetFindV0s()) AliITSV0Finder::FindV02(event,this);
   fAfterV0 = kTRUE;
-  //GetBestHypothesysMIP(itsTracks);
   //
-  itsTracks.Delete();
+  itsTracks.Clear();
   //
   Int_t entries = fTrackHypothesys.GetEntriesFast();
   for (Int_t ientry=0; ientry<entries; ientry++) {
@@ -502,13 +640,19 @@ Int_t AliITStrackerMI::Clusters2Tracks(AliESDEvent *event) {
   }
 
   fTrackHypothesys.Delete();
+  entries = fBestHypothesys.GetEntriesFast();
+  for (Int_t ientry=0; ientry<entries; ientry++) {
+    TObjArray * array =(TObjArray*)fBestHypothesys.UncheckedAt(ientry);
+    if (array) array->Delete();
+    delete fBestHypothesys.RemoveAt(ientry);
+  }
   fBestHypothesys.Delete();
   fOriginal.Clear();
   delete [] fCoefficients;
   fCoefficients=0;
   DeleteTrksMaterialLUT();
 
-  Info("Clusters2Tracks","Number of prolonged tracks: %d\n",ntrk);
+  AliInfo(Form("Number of prolonged tracks: %d out of %d ESD tracks",ntrk,noesd));
 
   fTrackingPhase="Default";
   
@@ -522,7 +666,7 @@ Int_t AliITStrackerMI::PropagateBack(AliESDEvent *event) {
   //--------------------------------------------------------------------
   fTrackingPhase="PropagateBack";
   Int_t nentr=event->GetNumberOfTracks();
-  Info("PropagateBack", "Number of ESD tracks: %d\n", nentr);
+  //  Info("PropagateBack", "Number of ESD tracks: %d\n", nentr);
 
   Int_t ntrk=0;
   for (Int_t i=0; i<nentr; i++) {
@@ -531,18 +675,13 @@ Int_t AliITStrackerMI::PropagateBack(AliESDEvent *event) {
      if ((esd->GetStatus()&AliESDtrack::kITSin)==0) continue;
      if (esd->GetStatus()&AliESDtrack::kITSout) continue;
 
-     AliITStrackMI *t=0;
-     try {
-        t=new AliITStrackMI(*esd);
-     } catch (const Char_t *msg) {
-       //Warning("PropagateBack",msg);
-        delete t;
-        continue;
-     }
+     AliITStrackMI *t = new AliITStrackMI(*esd);
+
      t->SetExpQ(TMath::Max(0.8*t->GetESDtrack()->GetTPCsignal(),30.));
 
      ResetTrackToFollow(*t);
 
+     /*
      // propagate to vertex [SR, GSI 17.02.2003]
      // Start Time measurement [SR, GSI 17.02.2003], corrected by I.Belikov
      if (CorrectForPipeMaterial(&fTrackToFollow,"inward")) {
@@ -550,7 +689,17 @@ Int_t AliITStrackerMI::PropagateBack(AliESDEvent *event) {
         fTrackToFollow.StartTimeIntegral();
        // from vertex to outside pipe
        CorrectForPipeMaterial(&fTrackToFollow,"outward");
+       }*/
+     // Start time integral and add distance from current position to vertex 
+     Double_t xyzTrk[3],xyzVtx[3]={GetX(),GetY(),GetZ()};
+     fTrackToFollow.GetXYZ(xyzTrk);
+     Double_t dst2 = 0.;
+     for (Int_t icoord=0; icoord<3; icoord++) {  
+       Double_t di = xyzTrk[icoord] - xyzVtx[icoord];
+       dst2 += di*di; 
      }
+     fTrackToFollow.StartTimeIntegral();
+     fTrackToFollow.AddTimeStep(TMath::Sqrt(dst2));
 
      fTrackToFollow.ResetCovariance(10.); fTrackToFollow.ResetClusters();
      if (RefitAt(AliITSRecoParam::GetrInsideITSscreen(),&fTrackToFollow,t)) {
@@ -568,7 +717,7 @@ Int_t AliITStrackerMI::PropagateBack(AliESDEvent *event) {
      delete t;
   }
 
-  Info("PropagateBack","Number of back propagated ITS tracks: %d\n",ntrk);
+  AliInfo(Form("Number of back propagated ITS tracks: %d out of %d ESD tracks",ntrk,nentr));
 
   fTrackingPhase="Default";
 
@@ -582,9 +731,14 @@ Int_t AliITStrackerMI::RefitInward(AliESDEvent *event) {
   // The clusters must be loaded !
   //--------------------------------------------------------------------
   fTrackingPhase="RefitInward";
-  if(AliITSReconstructor::GetRecoParam()->GetFindV0s()) RefitV02(event);
+
+  if(AliITSReconstructor::GetRecoParam()->GetFindV0s()) AliITSV0Finder::RefitV02(event,this);
+
+  Bool_t doExtra=AliITSReconstructor::GetRecoParam()->GetSearchForExtraClusters();
+  if(!doExtra) AliDebug(2,"Do not search for extra clusters");
+
   Int_t nentr=event->GetNumberOfTracks();
-  Info("RefitInward", "Number of ESD tracks: %d\n", nentr);
+  //  Info("RefitInward", "Number of ESD tracks: %d\n", nentr);
 
   Int_t ntrk=0;
   for (Int_t i=0; i<nentr; i++) {
@@ -595,14 +749,8 @@ Int_t AliITStrackerMI::RefitInward(AliESDEvent *event) {
     if (esd->GetStatus()&AliESDtrack::kTPCout)
       if ((esd->GetStatus()&AliESDtrack::kTPCrefit)==0) continue;
 
-    AliITStrackMI *t=0;
-    try {
-        t=new AliITStrackMI(*esd);
-    } catch (const Char_t *msg) {
-      //Warning("RefitInward",msg);
-        delete t;
-        continue;
-    }
+    AliITStrackMI *t = new AliITStrackMI(*esd);
+
     t->SetExpQ(TMath::Max(0.8*t->GetESDtrack()->GetTPCsignal(),30.));
     if (!CorrectForTPCtoITSDeadZoneMaterial(t)) {
        delete t;
@@ -612,11 +760,24 @@ Int_t AliITStrackerMI::RefitInward(AliESDEvent *event) {
     ResetTrackToFollow(*t);
     fTrackToFollow.ResetClusters();
 
-    if ((esd->GetStatus()&AliESDtrack::kTPCin)==0)
+    // ITS standalone tracks
+    if ((esd->GetStatus()&AliESDtrack::kTPCin)==0) {
       fTrackToFollow.ResetCovariance(10.);
+      // protection for loopers that can have parameters screwed up
+      if(TMath::Abs(fTrackToFollow.GetY())>1000. ||
+        TMath::Abs(fTrackToFollow.GetZ())>1000.) {
+       delete t;
+       continue;
+      }
+    }
 
     //Refitting...
-    if (RefitAt(AliITSRecoParam::GetrInsideSPD1(), &fTrackToFollow, t,kTRUE)) {
+    Bool_t pe=(AliITSReconstructor::GetRecoParam()->GetComputePlaneEff() &&
+               AliITSReconstructor::GetRecoParam()->GetIPlanePlaneEff()>=0);
+
+    AliDebug(2,Form("Refit LABEL %d  %d",t->GetLabel(),t->GetNumberOfClusters()));
+    if (RefitAt(AliITSRecoParam::GetrInsideSPD1(),&fTrackToFollow,t,doExtra,pe)) {
+       AliDebug(2,"  refit OK");
        fTrackToFollow.SetLabel(t->GetLabel());
        //       fTrackToFollow.CookdEdx();
        CookdEdx(&fTrackToFollow);
@@ -625,9 +786,11 @@ Int_t AliITStrackerMI::RefitInward(AliESDEvent *event) {
 
        //The beam pipe
        if (CorrectForPipeMaterial(&fTrackToFollow,"inward")) {
+        fTrackToFollow.UpdateESDtrack(AliESDtrack::kITSrefit);
         AliESDtrack  *esdTrack =fTrackToFollow.GetESDtrack();
-        esdTrack->UpdateTrackParams(&fTrackToFollow,AliESDtrack::kITSrefit);
-        Float_t r[3]={0.,0.,0.};
+        //printf("                                       %d\n",esdTrack->GetITSModuleIndex(0));
+        //esdTrack->UpdateTrackParams(&fTrackToFollow,AliESDtrack::kITSrefit); //original line
+        Double_t r[3]={0.,0.,0.};
         Double_t maxD=3.;
         esdTrack->RelateToVertex(event->GetVertex(),GetBz(r),maxD);
         ntrk++;
@@ -636,7 +799,7 @@ Int_t AliITStrackerMI::RefitInward(AliESDEvent *event) {
     delete t;
   }
 
-  Info("RefitInward","Number of refitted tracks: %d\n",ntrk);
+  AliInfo(Form("Number of refitted tracks: %d out of %d ESD tracks",ntrk,nentr));
 
   fTrackingPhase="Default";
 
@@ -667,7 +830,10 @@ Bool_t AliITStrackerMI::GetTrackPoint(Int_t index, AliTrackPoint& p) const {
   cl->GetGlobalXYZ(xyz);
   cl->GetGlobalCov(cov);
   p.SetXYZ(xyz, cov);
-
+  p.SetCharge(cl->GetQ());
+  p.SetDriftTime(cl->GetDriftTime());
+  p.SetChargeRatio(cl->GetChargeRatio());
+  p.SetClusterType(cl->GetClusterType());
   AliGeomManager::ELayerID iLayer = AliGeomManager::kInvalidLayer; 
   switch (l) {
   case 0:
@@ -708,6 +874,7 @@ Bool_t AliITStrackerMI::GetTrackPointTrackingError(Int_t index,
   Int_t c=(index & 0x0fffffff) >> 00;
   const AliITSRecPoint *cl = fgLayers[l].GetCluster(c);
   Int_t idet = cl->GetDetectorIndex();
+
   const AliITSdetector &det=fgLayers[l].GetDetector(idet);
 
   // tgphi and tglambda of the track in tracking frame with alpha=det.GetPhi
@@ -716,25 +883,30 @@ Bool_t AliITStrackerMI::GetTrackPointTrackingError(Int_t index,
   detxy[1] = det.GetR()*TMath::Sin(det.GetPhi());
   Double_t alpha = t->GetAlpha();
   Double_t xdetintrackframe = detxy[0]*TMath::Cos(alpha)+detxy[1]*TMath::Sin(alpha);
-  Float_t phi = TMath::ASin(t->GetSnpAt(xdetintrackframe,AliTracker::GetBz()));
+  Float_t phi = TMath::ASin(t->GetSnpAt(xdetintrackframe+cl->GetX(),GetBz()));
   phi += alpha-det.GetPhi();
   Float_t tgphi = TMath::Tan(phi);
 
   Float_t tgl = t->GetTgl(); // tgl about const along track
   Float_t expQ = TMath::Max(0.8*t->GetTPCsignal(),30.);
 
-  Float_t errlocalx,errlocalz;
-  AliITSClusterParam::GetError(l,cl,tgl,tgphi,expQ,errlocalx,errlocalz);
+  Float_t errtrky,errtrkz,covyz;
+  Bool_t addMisalErr=kFALSE;
+  AliITSClusterParam::GetError(l,cl,tgl,tgphi,expQ,errtrky,errtrkz,covyz,addMisalErr);
 
   Float_t xyz[3];
   Float_t cov[6];
   cl->GetGlobalXYZ(xyz);
   //  cl->GetGlobalCov(cov);
   Float_t pos[3] = {0.,0.,0.};
-  AliCluster tmpcl((UShort_t)cl->GetVolumeId(),pos[0],pos[1],pos[2],errlocalx*errlocalx,errlocalz*errlocalz,0);
+  AliCluster tmpcl((UShort_t)cl->GetVolumeId(),pos[0],pos[1],pos[2],errtrky*errtrky,errtrkz*errtrkz,covyz);
   tmpcl.GetGlobalCov(cov);
 
   p.SetXYZ(xyz, cov);
+  p.SetCharge(cl->GetQ());
+  p.SetDriftTime(cl->GetDriftTime());
+  p.SetChargeRatio(cl->GetChargeRatio());
+  p.SetClusterType(cl->GetClusterType());
 
   AliGeomManager::ELayerID iLayer = AliGeomManager::kInvalidLayer; 
   switch (l) {
@@ -761,6 +933,7 @@ Bool_t AliITStrackerMI::GetTrackPointTrackingError(Int_t index,
     break;
   };
   UShort_t volid = AliGeomManager::LayerToVolUID(iLayer,idet);
+
   p.SetVolumeID((UShort_t)volid);
   return kTRUE;
 }
@@ -797,6 +970,7 @@ void AliITStrackerMI::FollowProlongationTree(AliITStrackMI * otrack, Int_t esdin
   TObjArray *bestarray = (TObjArray*)fBestHypothesys.At(esdindex);
   if (!bestarray){
     bestarray = new TObjArray(5);
+    bestarray->SetOwner();
     fBestHypothesys.AddAt(bestarray,esdindex);
   }
 
@@ -816,10 +990,13 @@ void AliITStrackerMI::FollowProlongationTree(AliITStrackMI * otrack, Int_t esdin
   new (&(tracks[6][0])) AliITStrackMI(*otrack);
   ntracks[6]=1;
   for (Int_t i=0;i<7;i++) nindexes[i][0]=0;
+  Int_t modstatus = 1; // found 
+  Float_t xloc,zloc;
   // 
   //
   // follow prolongations
   for (Int_t ilayer=5; ilayer>=0; ilayer--) {
+    AliDebug(2,Form("FollowProlongationTree: layer %d",ilayer));
     fI = ilayer;
     //
     AliITSlayer &layer=fgLayers[ilayer];
@@ -853,22 +1030,30 @@ void AliITStrackerMI::FollowProlongationTree(AliITStrackMI * otrack, Int_t esdin
       Int_t idet=layer.FindDetectorIndex(phi,z);
 
       Double_t trackGlobXYZ1[3];
-      currenttrack1.GetXYZ(trackGlobXYZ1);
+      if (!currenttrack1.GetXYZ(trackGlobXYZ1)) continue;
 
       // Get the budget to the primary vertex for the current track being prolonged
       Double_t budgetToPrimVertex = GetEffectiveThickness();
 
       // check if we allow a prolongation without point
-      Int_t skip = SkipLayer(&currenttrack1,ilayer,idet);
+      Int_t skip = CheckSkipLayer(&currenttrack1,ilayer,idet);
       if (skip) {
        AliITStrackMI* vtrack = new (&tracks[ilayer][ntracks[ilayer]]) AliITStrackMI(currenttrack1);
+       // propagate to the layer radius
+       Double_t xToGo; if (!vtrack->GetLocalXat(r,xToGo)) continue;
+       if(!vtrack->Propagate(xToGo)) continue;
        // apply correction for material of the current layer
        CorrectForLayerMaterial(vtrack,ilayer,trackGlobXYZ1,"inward");
        vtrack->SetNDeadZone(vtrack->GetNDeadZone()+1);
-       vtrack->SetClIndex(ilayer,0);
-       if(constrain) vtrack->Improve(budgetToPrimVertex,xyzVtx,ersVtx);
+       vtrack->SetDeadZoneProbability(ilayer,1.); // no penalty for missing cluster
+       vtrack->SetClIndex(ilayer,-1);
+       modstatus = (skip==1 ? 3 : 4); // skipped : out in z
+       if(LocalModuleCoord(ilayer,idet,vtrack,xloc,zloc)) { // local module coords
+         vtrack->SetModuleIndexInfo(ilayer,idet,modstatus,xloc,zloc);
+       }
+       if(constrain && AliITSReconstructor::GetRecoParam()->GetImproveWithVertex()) vtrack->Improve(budgetToPrimVertex,xyzVtx,ersVtx);
        ntracks[ilayer]++;
-       continue;  //if (skip==1 || skip==2) continue;
+       continue;
       }
 
       // track outside layer acceptance in z
@@ -878,44 +1063,17 @@ void AliITStrackerMI::FollowProlongationTree(AliITStrackMI * otrack, Int_t esdin
       const AliITSdetector &det=layer.GetDetector(idet);
       new(&currenttrack2)  AliITStrackMI(currenttrack1);
       if (!currenttrack1.Propagate(det.GetPhi(),det.GetR())) continue;
-      currenttrack2.Propagate(det.GetPhi(),det.GetR());
+      if (!currenttrack2.Propagate(det.GetPhi(),det.GetR())) continue;
       currenttrack1.SetDetectorIndex(idet);
       currenttrack2.SetDetectorIndex(idet);
-      
+      if(!LocalModuleCoord(ilayer,idet,&currenttrack1,xloc,zloc)) continue; // local module coords
+
       //***************
-      // DEFINITION OF SEARCH ROAD FOR CLUSTERS SELECTION
+      // DEFINITION OF SEARCH ROAD AND CLUSTERS SELECTION
       //
-      Double_t dz=AliITSReconstructor::GetRecoParam()->GetNSigmaRoadZ()*
-                    TMath::Sqrt(currenttrack1.GetSigmaZ2() + 
-                   AliITSReconstructor::GetRecoParam()->GetNSigmaZLayerForRoadZ()*
-                   AliITSReconstructor::GetRecoParam()->GetNSigmaZLayerForRoadZ()*
-                   AliITSReconstructor::GetRecoParam()->GetSigmaZ2(ilayer));
-      Double_t dy=AliITSReconstructor::GetRecoParam()->GetNSigmaRoadY()*
-                    TMath::Sqrt(currenttrack1.GetSigmaY2() + 
-                   AliITSReconstructor::GetRecoParam()->GetNSigmaYLayerForRoadY()*
-                   AliITSReconstructor::GetRecoParam()->GetNSigmaYLayerForRoadY()*
-                   AliITSReconstructor::GetRecoParam()->GetSigmaY2(ilayer));
-      
-      // track at boundary between detectors, enlarge road
-      Double_t boundaryWidth=AliITSRecoParam::GetBoundaryWidth();
-      if ( (currenttrack1.GetY()-dy < det.GetYmin()+boundaryWidth) || 
-          (currenttrack1.GetY()+dy > det.GetYmax()-boundaryWidth) || 
-          (currenttrack1.GetZ()-dz < det.GetZmin()+boundaryWidth) ||
-          (currenttrack1.GetZ()+dz > det.GetZmax()-boundaryWidth) ) {
-       Float_t tgl = TMath::Abs(currenttrack1.GetTgl());
-       if (tgl > 1.) tgl=1.;
-       Double_t deltaXNeighbDets=AliITSRecoParam::GetDeltaXNeighbDets();
-       dz = TMath::Sqrt(dz*dz+deltaXNeighbDets*deltaXNeighbDets*tgl*tgl);
-       Float_t snp = TMath::Abs(currenttrack1.GetSnp());
-       if (snp > AliITSReconstructor::GetRecoParam()->GetMaxSnp()) continue;
-       dy = TMath::Sqrt(dy*dy+deltaXNeighbDets*deltaXNeighbDets*snp*snp);
-      } // boundary
-      
       // road in global (rphi,z) [i.e. in tracking ref. system]
-      Double_t zmin = currenttrack1.GetZ() - dz; 
-      Double_t zmax = currenttrack1.GetZ() + dz;
-      Double_t ymin = currenttrack1.GetY() + r*det.GetPhi() - dy;
-      Double_t ymax = currenttrack1.GetY() + r*det.GetPhi() + dy;
+      Double_t zmin,zmax,ymin,ymax;
+      if (!ComputeRoad(&currenttrack1,ilayer,idet,zmin,zmax,ymin,ymax)) continue;
 
       // select clusters in road
       layer.SelectClusters(zmin,zmax,ymin,ymax); 
@@ -939,6 +1097,7 @@ void AliITStrackerMI::FollowProlongationTree(AliITStrackMI * otrack, Int_t esdin
       }
       msz = 1./msz; // 1/RoadZ^2
       msy = 1./msy; // 1/RoadY^2
+
       //
       //
       // LOOP OVER ALL POSSIBLE TRACK PROLONGATIONS ON THIS LAYER
@@ -946,25 +1105,88 @@ void AliITStrackerMI::FollowProlongationTree(AliITStrackMI * otrack, Int_t esdin
       const AliITSRecPoint *cl=0; 
       Int_t clidx=-1;
       Double_t chi2trkcl=AliITSReconstructor::GetRecoParam()->GetMaxChi2(); // init with big value
-      Int_t deadzone=0;
+      Bool_t deadzoneSPD=kFALSE;
       currenttrack = &currenttrack1;
-      // loop over selected clusters
+
+      // check if the road contains a dead zone 
+      Bool_t noClusters = kFALSE;
+      if (!layer.GetNextCluster(clidx,kTRUE)) noClusters=kTRUE;
+      if (noClusters) AliDebug(2,"no clusters in road");
+      Double_t dz=0.5*(zmax-zmin);
+      Double_t dy=0.5*(ymax-ymin);
+      Int_t dead = CheckDeadZone(&currenttrack1,ilayer,idet,dz,dy,noClusters); 
+      if(dead) AliDebug(2,Form("DEAD (%d)\n",dead));
+      // create a prolongation without clusters (check also if there are no clusters in the road)
+      if (dead || 
+         (noClusters && 
+          AliITSReconstructor::GetRecoParam()->GetAllowProlongationWithEmptyRoad())) {
+       AliITStrackMI * updatetrack = new (&tracks[ilayer][ntracks[ilayer]]) AliITStrackMI(*currenttrack);
+       updatetrack->SetClIndex(ilayer,-1);
+       if (dead==0) {
+         modstatus = 5; // no cls in road
+       } else if (dead==1) {
+         modstatus = 7; // holes in z in SPD
+       } else if (dead==2 || dead==3 || dead==4) {
+         modstatus = 2; // dead from OCDB
+       }
+       updatetrack->SetModuleIndexInfo(ilayer,idet,modstatus,xloc,zloc);
+       // apply correction for material of the current layer
+       CorrectForLayerMaterial(updatetrack,ilayer,trackGlobXYZ1,"inward");
+       if (constrain) { // apply vertex constrain
+         updatetrack->SetConstrain(constrain);
+         Bool_t isPrim = kTRUE;
+         if (ilayer<4) { // check that it's close to the vertex
+           updatetrack->GetDZ(GetX(),GetY(),GetZ(),updatetrack->GetDP()); //I.B.
+           if (TMath::Abs(updatetrack->GetD(0)/(1.+ilayer)) > // y
+               AliITSReconstructor::GetRecoParam()->GetMaxDZforPrimTrk() || 
+               TMath::Abs(updatetrack->GetD(1)/(1.+ilayer)) > // z
+               AliITSReconstructor::GetRecoParam()->GetMaxDZforPrimTrk()) isPrim=kFALSE;
+         }
+         if (isPrim && AliITSReconstructor::GetRecoParam()->GetImproveWithVertex()) updatetrack->Improve(budgetToPrimVertex,xyzVtx,ersVtx);
+       }
+       updatetrack->SetNDeadZone(updatetrack->GetNDeadZone()+1);
+       if (dead) {
+         if (dead==1) { // dead zone at z=0,+-7cm in SPD
+           updatetrack->SetDeadZoneProbability(ilayer,GetSPDDeadZoneProbability(updatetrack->GetZ(),TMath::Sqrt(updatetrack->GetSigmaZ2())));
+           deadzoneSPD=kTRUE;
+         } else if (dead==2 || dead==3) { // dead module or chip from OCDB  
+           updatetrack->SetDeadZoneProbability(ilayer,1.); 
+         } else if (dead==4) { // at least a single dead channel from OCDB  
+           updatetrack->SetDeadZoneProbability(ilayer,0.); 
+         } 
+       }
+       ntracks[ilayer]++;
+      }
+
+      clidx=-1;
+      // loop over clusters in the road
       while ((cl=layer.GetNextCluster(clidx))!=0) { 
        if (ntracks[ilayer]>95) break; //space for skipped clusters  
        Bool_t changedet =kFALSE;  
-       if (cl->GetQ()==0 && (deadzone==1)) continue;
-       Int_t idet=cl->GetDetectorIndex();
+       if (TMath::Abs(cl->GetQ())<1.e-13 && deadzoneSPD==kTRUE) continue;
+       Int_t idetc=cl->GetDetectorIndex();
 
-       if (currenttrack->GetDetectorIndex()==idet) { // track already on the cluster's detector
+       if (currenttrack->GetDetectorIndex()==idetc) { // track already on the cluster's detector
+         // take into account misalignment (bring track to real detector plane)
+         Double_t xTrOrig = currenttrack->GetX();
+         if (!currenttrack->Propagate(xTrOrig+cl->GetX())) continue;
          // a first cut on track-cluster distance
          if ( (currenttrack->GetZ()-cl->GetZ())*(currenttrack->GetZ()-cl->GetZ())*msz + 
               (currenttrack->GetY()-cl->GetY())*(currenttrack->GetY()-cl->GetY())*msy > 1. ) 
-           continue; // cluster not associated to track
+           {  // cluster not associated to track
+             AliDebug(2,"not associated");
+             // MvL: added here as well
+             // bring track back to ideal detector plane
+             currenttrack->Propagate(xTrOrig);
+             continue;
+           }
+         // bring track back to ideal detector plane
+         if (!currenttrack->Propagate(xTrOrig)) continue;
        } else {                                      // have to move track to cluster's detector
-         const AliITSdetector &det=layer.GetDetector(idet);
+         const AliITSdetector &detc=layer.GetDetector(idetc);
          // a first cut on track-cluster distance
-         Double_t y,z;
-         if (!currenttrack2.GetProlongationFast(det.GetPhi(),det.GetR(),y,z)) continue;
+         Double_t y;
+         if (!currenttrack2.GetProlongationFast(detc.GetPhi(),detc.GetR()+cl->GetX(),y,z)) continue;
          if ( (z-cl->GetZ())*(z-cl->GetZ())*msz + 
               (y-cl->GetY())*(y-cl->GetY())*msy > 1. ) 
            continue; // cluster not associated to track
@@ -972,12 +1194,12 @@ void AliITStrackerMI::FollowProlongationTree(AliITStrackMI * otrack, Int_t esdin
          new (&backuptrack) AliITStrackMI(currenttrack2);
          changedet = kTRUE;
          currenttrack =&currenttrack2;
-         if (!currenttrack->Propagate(det.GetPhi(),det.GetR())) {
+         if (!currenttrack->Propagate(detc.GetPhi(),detc.GetR())) {
            new (currenttrack) AliITStrackMI(backuptrack);
            changedet = kFALSE;
            continue;
          }
-         currenttrack->SetDetectorIndex(idet);
+         currenttrack->SetDetectorIndex(idetc);
          // Get again the budget to the primary vertex 
          // for the current track being prolonged, if had to change detector 
          //budgetToPrimVertex = GetEffectiveThickness();// not needed at the moment because anyway we take a mean material for this correction
@@ -986,19 +1208,34 @@ void AliITStrackerMI::FollowProlongationTree(AliITStrackMI * otrack, Int_t esdin
        // calculate track-clusters chi2
        chi2trkcl = GetPredictedChi2MI(currenttrack,cl,ilayer); 
        // chi2 cut
+       AliDebug(2,Form("chi2 %f max %f",chi2trkcl,AliITSReconstructor::GetRecoParam()->GetMaxChi2s(ilayer)));
        if (chi2trkcl < AliITSReconstructor::GetRecoParam()->GetMaxChi2s(ilayer)) {
-         if (cl->GetQ()==0) deadzone=1;            // take dead zone only once   
+         if (TMath::Abs(cl->GetQ())<1.e-13) deadzoneSPD=kTRUE; // only 1 prolongation with virtual cluster       
          if (ntracks[ilayer]>=100) continue;
          AliITStrackMI * updatetrack = new (&tracks[ilayer][ntracks[ilayer]]) AliITStrackMI(*currenttrack);
-         updatetrack->SetClIndex(ilayer,0);
+         updatetrack->SetClIndex(ilayer,-1);
          if (changedet) new (&currenttrack2) AliITStrackMI(backuptrack);
-         
-         if (cl->GetQ()!=0) {
-           if (!UpdateMI(updatetrack,cl,chi2trkcl,(ilayer<<28)+clidx)) continue; 
-           updatetrack->SetSampledEdx(cl->GetQ(),updatetrack->GetNumberOfClusters()-1); //b.b.
-         } else { // cluster in dead zone
+
+         if (TMath::Abs(cl->GetQ())>1.e-13) { // real cluster
+           if (!UpdateMI(updatetrack,cl,chi2trkcl,(ilayer<<28)+clidx)) {
+             AliDebug(2,"update failed");
+             continue;
+           } 
+           updatetrack->SetSampledEdx(cl->GetQ(),ilayer-2); 
+           modstatus = 1; // found
+         } else {             // virtual cluster in dead zone
            updatetrack->SetNDeadZone(updatetrack->GetNDeadZone()+1);
-           updatetrack->SetDeadZoneProbability(GetDeadZoneProbability(updatetrack->GetZ(),TMath::Sqrt(updatetrack->GetSigmaZ2())));
+           updatetrack->SetDeadZoneProbability(ilayer,GetSPDDeadZoneProbability(updatetrack->GetZ(),TMath::Sqrt(updatetrack->GetSigmaZ2())));
+           modstatus = 7; // holes in z in SPD
+         }
+
+         if (changedet) {
+           Float_t xlocnewdet,zlocnewdet;
+           if(LocalModuleCoord(ilayer,idet,updatetrack,xlocnewdet,zlocnewdet)) { // local module coords
+             updatetrack->SetModuleIndexInfo(ilayer,idet,modstatus,xlocnewdet,zlocnewdet);
+           }
+         } else {
+           updatetrack->SetModuleIndexInfo(ilayer,idet,modstatus,xloc,zloc);
          }
          if (cl->IsUsed()) updatetrack->IncrementNUsed();
 
@@ -1015,35 +1252,30 @@ void AliITStrackerMI::FollowProlongationTree(AliITStrackMI * otrack, Int_t esdin
                  TMath::Abs(updatetrack->GetD(1)/(1.+ilayer)) > // z
                  AliITSReconstructor::GetRecoParam()->GetMaxDZforPrimTrk()) isPrim=kFALSE;
            }
-           if (isPrim) updatetrack->Improve(budgetToPrimVertex,xyzVtx,ersVtx);
+           if (isPrim && AliITSReconstructor::GetRecoParam()->GetImproveWithVertex()) updatetrack->Improve(budgetToPrimVertex,xyzVtx,ersVtx);
          } //apply vertex constrain              
          ntracks[ilayer]++;
        }  // create new hypothesis
+       else {
+         AliDebug(2,"chi2 too large");
+       }
+
       } // loop over possible prolongations 
      
       // allow one prolongation without clusters
-      if (constrain && itrack<=1 && currenttrack1.GetNSkipped()==0 && deadzone==0 && ntracks[ilayer]<100) {
+      if (constrain && itrack<=1 && TMath::Abs(currenttrack1.GetNSkipped())<1.e-13 && deadzoneSPD==kFALSE && ntracks[ilayer]<100) {
        AliITStrackMI* vtrack = new (&tracks[ilayer][ntracks[ilayer]]) AliITStrackMI(currenttrack1);
        // apply correction for material of the current layer
        CorrectForLayerMaterial(vtrack,ilayer,trackGlobXYZ1,"inward");
-       vtrack->SetClIndex(ilayer,0);
-       vtrack->Improve(budgetToPrimVertex,xyzVtx,ersVtx);
+       vtrack->SetClIndex(ilayer,-1);
+       modstatus = 3; // skipped 
+       vtrack->SetModuleIndexInfo(ilayer,idet,modstatus,xloc,zloc);
+       if(AliITSReconstructor::GetRecoParam()->GetImproveWithVertex()) vtrack->Improve(budgetToPrimVertex,xyzVtx,ersVtx);
        vtrack->IncrementNSkipped();
        ntracks[ilayer]++;
       }
-
-      // allow one prolongation without clusters for tracks with |tgl|>1.1
-      if (constrain && itrack==0 && TMath::Abs(currenttrack1.GetTgl())>1.1) {  //big theta - for low flux
-       AliITStrackMI* vtrack = new (&tracks[ilayer][ntracks[ilayer]]) AliITStrackMI(currenttrack1);
-       // apply correction for material of the current layer
-       CorrectForLayerMaterial(vtrack,ilayer,trackGlobXYZ1,"inward");
-       vtrack->SetClIndex(ilayer,0);
-       vtrack->Improve(budgetToPrimVertex,xyzVtx,ersVtx);
-       vtrack->SetNDeadZone(vtrack->GetNDeadZone()+1);
-       ntracks[ilayer]++;
-      }
-     
       
+
     } // loop over tracks in layer ilayer+1
 
     //loop over track candidates for the current layer
@@ -1075,7 +1307,6 @@ void AliITStrackerMI::FollowProlongationTree(AliITStrackMI * otrack, Int_t esdin
     if (ntracks[ilayer]>90) ntracks[ilayer]=90; 
   } // end loop over layers
 
-  //printf("%d\t%d\t%d\t%d\t%d\t%d\n",ntracks[0],ntracks[1],ntracks[2],ntracks[3],ntracks[4],ntracks[5]);
 
   //
   // Now select tracks to be kept
@@ -1087,7 +1318,9 @@ void AliITStrackerMI::FollowProlongationTree(AliITStrackMI * otrack, Int_t esdin
     AliITStrackMI & track= tracks[0][nindexes[0][i]];
     if (track.GetNumberOfClusters()<2) continue;
     if (!constrain && track.GetNormChi2(0) >
-       AliITSReconstructor::GetRecoParam()->GetMaxNormChi2NonCForHypothesis()) continue;
+       AliITSReconstructor::GetRecoParam()->GetMaxNormChi2NonCForHypothesis()) {
+      continue;
+    }
     AddTrackHypothesys(new AliITStrackMI(track), esdindex);
   }
 
@@ -1108,20 +1341,17 @@ void AliITStrackerMI::FollowProlongationTree(AliITStrackMI * otrack, Int_t esdin
     AddTrackHypothesys(new AliITStrackMI(track), esdindex);
   }
 
-  // tracks that reack layer 2 (SDD inner), only during non-constrained pass
+  // tracks that reach layer 2 (SDD inner), only during non-constrained pass
   if (!constrain){  
     for (Int_t i=0;i<TMath::Min(2,ntracks[2]);i++) {
       AliITStrackMI & track= tracks[2][nindexes[2][i]];
       if (track.GetNumberOfClusters()<3) continue;
-      if (!constrain && track.GetNormChi2(2) >
+      if (track.GetNormChi2(2) >
          AliITSReconstructor::GetRecoParam()->GetMaxNormChi2NonCForHypothesis()) continue;
-      if (constrain) track.SetNSkipped(track.GetNSkipped()+2);      
-      if (!constrain){
-       track.SetD(0,track.GetD(GetX(),GetY()));
-       track.SetNSkipped(track.GetNSkipped()+7./(7.+8.*TMath::Abs(track.GetD(0))));
-       if (track.GetNumberOfClusters()+track.GetNDeadZone()+track.GetNSkipped()>6) {
-         track.SetNSkipped(6-track.GetNumberOfClusters()+track.GetNDeadZone());
-       }
+      track.SetD(0,track.GetD(GetX(),GetY()));
+      track.SetNSkipped(track.GetNSkipped()+7./(7.+8.*TMath::Abs(track.GetD(0))));
+      if (track.GetNumberOfClusters()+track.GetNDeadZone()+track.GetNSkipped()>6) {
+       track.SetNSkipped(6-track.GetNumberOfClusters()+track.GetNDeadZone());
       }
       AddTrackHypothesys(new AliITStrackMI(track), esdindex);
     }
@@ -1160,7 +1390,7 @@ void AliITStrackerMI::FollowProlongationTree(AliITStrackMI * otrack, Int_t esdin
       Double_t xrp[3]; vertex->GetXYZ(xrp[0],xrp[1],xrp[2]);  //I.B.
       Int_t nearestold  = GetNearestLayer(xrp);               //I.B.
       Int_t nearest     = nearestold; 
-      for (Int_t ilayer =nearest;ilayer<8;ilayer++){
+      for (Int_t ilayer =nearest;ilayer<7;ilayer++){
        if (ntracks[nearest]==0){
          nearest = ilayer;
        }
@@ -1216,6 +1446,7 @@ fYcs(0),
 fZcs(0),
 fNcs(0),
 fCurrentSlice(-1),
+fZmin(0),
 fZmax(0),
 fYmin(0),
 fYmax(0),
@@ -1223,7 +1454,11 @@ fI(0),
 fImax(0),
 fSkip(0),
 fAccepted(0),
-fRoad(0){
+fRoad(0),
+fMaxSigmaClY(0),
+fMaxSigmaClZ(0),
+fNMaxSigmaCl(3)
+{
   //--------------------------------------------------------------------
   //default AliITSlayer constructor
   //--------------------------------------------------------------------
@@ -1232,8 +1467,50 @@ fRoad(0){
     fClusterTracks[0][i]=-1;
     fClusterTracks[1][i]=-1;
     fClusterTracks[2][i]=-1;    
-    fClusterTracks[3][i]=-1;    
+    fClusterTracks[3][i]=-1;
+    fY[i]=0;    
+    fZ[i]=0;    
+  }
+  fYB[0]=0;
+  fYB[1]=0;
+
+  for (Int_t j=0; j<AliITSRecoParam::fgkMaxClusterPerLayer5; j++) {
+    for (Int_t j1=0; j1<6; j1++) {
+      fClusters5[j1][j]=0;
+      fClusterIndex5[j1][j]=-1;
+      fY5[j1][j]=0;
+      fZ5[j1][j]=0;
+      fN5[j1]=0;
+      fBy5[j1][0]=0;
+      fBy5[j1][1]=0;
+    }
+  }
+
+  for (Int_t j=0; j<AliITSRecoParam::fgkMaxClusterPerLayer10; j++) {
+    for (Int_t j1=0; j1<11; j1++) {
+      fClusters10[j1][j]=0;
+      fClusterIndex10[j1][j]=-1;
+      fY10[j1][j]=0;
+      fZ10[j1][j]=0;
+      fN10[j1]=0;
+      fBy10[j1][0]=0;
+      fBy10[j1][1]=0;
+    }
+  }
+
+  for (Int_t j=0; j<AliITSRecoParam::fgkMaxClusterPerLayer20; j++) {
+    for (Int_t j1=0; j1<21; j1++) {
+      fClusters20[j1][j]=0;
+      fClusterIndex20[j1][j]=-1;
+      fY20[j1][j]=0;
+      fZ20[j1][j]=0;
+      fN20[j1]=0;
+      fBy20[j1][0]=0;
+      fBy20[j1][1]=0;
+    }
   }
+  for(Int_t i=0;i<AliITSRecoParam::fgkMaxClusterPerLayer;i++)fClusters[i]=NULL;
+
 }
 //------------------------------------------------------------------------
 AliITStrackerMI::AliITSlayer::
@@ -1254,6 +1531,7 @@ fYcs(0),
 fZcs(0),
 fNcs(0),
 fCurrentSlice(-1),
+fZmin(0),
 fZmax(0),
 fYmin(0),
 fYmax(0),
@@ -1261,13 +1539,67 @@ fI(0),
 fImax(0),
 fSkip(0),
 fAccepted(0),
-fRoad(0) {
+fRoad(0),
+fMaxSigmaClY(0),
+fMaxSigmaClZ(0),
+fNMaxSigmaCl(3) {
   //--------------------------------------------------------------------
   //main AliITSlayer constructor
   //--------------------------------------------------------------------
   fDetectors=new AliITSdetector[fNladders*fNdetectors];
   fRoad=2*fR*TMath::Sqrt(TMath::Pi()/1.);//assuming that there's only one cluster
+
+  for (Int_t i=0; i<AliITSRecoParam::GetMaxClusterPerLayer(); i++) {
+    fClusterWeight[i]=0;
+    fClusterTracks[0][i]=-1;
+    fClusterTracks[1][i]=-1;
+    fClusterTracks[2][i]=-1;    
+    fClusterTracks[3][i]=-1;    
+    fY[i]=0;    
+    fZ[i]=0;    
+  }
+
+  fYB[0]=0;
+  fYB[1]=0;
+
+  for (Int_t j=0; j<AliITSRecoParam::fgkMaxClusterPerLayer5; j++) {
+    for (Int_t j1=0; j1<6; j1++) {
+      fClusters5[j1][j]=0;
+      fClusterIndex5[j1][j]=-1;
+      fY5[j1][j]=0;
+      fZ5[j1][j]=0;
+      fN5[j1]=0;
+      fBy5[j1][0]=0;
+      fBy5[j1][1]=0;
+    }
+  }
+
+  for (Int_t j=0; j<AliITSRecoParam::fgkMaxClusterPerLayer10; j++) {
+    for (Int_t j1=0; j1<11; j1++) {
+      fClusters10[j1][j]=0;
+      fClusterIndex10[j1][j]=-1;
+      fY10[j1][j]=0;
+      fZ10[j1][j]=0;
+      fN10[j1]=0;
+      fBy10[j1][0]=0;
+      fBy10[j1][1]=0;
+    }
+  }
+
+  for (Int_t j=0; j<AliITSRecoParam::fgkMaxClusterPerLayer20; j++) {
+    for (Int_t j1=0; j1<21; j1++) {
+      fClusters20[j1][j]=0;
+      fClusterIndex20[j1][j]=-1;
+      fY20[j1][j]=0;
+      fZ20[j1][j]=0;
+      fN20[j1]=0;
+      fBy20[j1][0]=0;
+      fBy20[j1][1]=0;
+    }
+  }
+  for(Int_t i=0;i<AliITSRecoParam::fgkMaxClusterPerLayer;i++)fClusters[i]=NULL;
 }
+/*
 //------------------------------------------------------------------------
 AliITStrackerMI::AliITSlayer::AliITSlayer(const AliITSlayer& layer):
 fR(layer.fR),
@@ -1286,6 +1618,7 @@ fYcs(layer.fYcs),
 fZcs(layer.fZcs),
 fNcs(layer.fNcs),
 fCurrentSlice(layer.fCurrentSlice),
+fZmin(layer.fZmin),
 fZmax(layer.fZmax),
 fYmin(layer.fYmin),
 fYmax(layer.fYmax),
@@ -1293,15 +1626,20 @@ fI(layer.fI),
 fImax(layer.fImax),
 fSkip(layer.fSkip),
 fAccepted(layer.fAccepted),
-fRoad(layer.fRoad){
+fRoad(layer.fRoad),
+fMaxSigmaClY(layer.fMaxSigmaClY),
+fMaxSigmaClZ(layer.fMaxSigmaClZ),
+fNMaxSigmaCl(layer.fNMaxSigmaCl)
+{
   //Copy constructor
 }
+*/
 //------------------------------------------------------------------------
 AliITStrackerMI::AliITSlayer::~AliITSlayer() {
   //--------------------------------------------------------------------
   // AliITSlayer destructor
   //--------------------------------------------------------------------
-  delete[] fDetectors;
+  delete [] fDetectors;
   for (Int_t i=0; i<fN; i++) delete fClusters[i];
   for (Int_t i=0; i<AliITSRecoParam::GetMaxClusterPerLayer(); i++) {
     fClusterWeight[i]=0;
@@ -1363,18 +1701,26 @@ Int_t AliITStrackerMI::AliITSlayer::InsertCluster(AliITSRecPoint *cl) {
   //This function adds a cluster to this layer
   //--------------------------------------------------------------------
   if (fN==AliITSRecoParam::GetMaxClusterPerLayer()) {
-    ::Error("InsertCluster","Too many clusters !\n");
     return 1;
   }
   fCurrentSlice=-1;
   fClusters[fN]=cl;
   fN++;
   AliITSdetector &det=GetDetector(cl->GetDetectorIndex());    
+  //AD
+  Double_t nSigmaY=fNMaxSigmaCl*TMath::Sqrt(cl->GetSigmaY2());
+  Double_t nSigmaZ=fNMaxSigmaCl*TMath::Sqrt(cl->GetSigmaZ2()); 
+  if (cl->GetY()-nSigmaY<det.GetYmin()) det.SetYmin(cl->GetY()-nSigmaY);
+  if (cl->GetY()+nSigmaY>det.GetYmax()) det.SetYmax(cl->GetY()+nSigmaY);
+  if (cl->GetZ()-nSigmaZ<det.GetZmin()) det.SetZmin(cl->GetZ()-nSigmaZ);
+  if (cl->GetZ()+nSigmaZ>det.GetZmax()) det.SetZmax(cl->GetZ()+nSigmaZ);
+  //AD              
+  /*
   if (cl->GetY()<det.GetYmin()) det.SetYmin(cl->GetY());
   if (cl->GetY()>det.GetYmax()) det.SetYmax(cl->GetY());
   if (cl->GetZ()<det.GetZmin()) det.SetZmin(cl->GetZ());
   if (cl->GetZ()>det.GetZmax()) det.SetZmax(cl->GetZ());
-                            
+  */                
   return 0;
 }
 //------------------------------------------------------------------------
@@ -1387,8 +1733,14 @@ void  AliITStrackerMI::AliITSlayer::SortClusters()
   Float_t *z                = new Float_t[fN];
   Int_t   * index           = new Int_t[fN];
   //
+  fMaxSigmaClY=0.; //AD
+  fMaxSigmaClZ=0.; //AD
+
   for (Int_t i=0;i<fN;i++){
     z[i] = fClusters[i]->GetZ();
+    // save largest errors in y and z for this layer
+    fMaxSigmaClY=TMath::Max(fMaxSigmaClY,TMath::Sqrt(fClusters[i]->GetSigmaY2()));
+    fMaxSigmaClZ=TMath::Max(fMaxSigmaClZ,TMath::Sqrt(fClusters[i]->GetSigmaZ2()));
   }
   TMath::Sort(fN,z,index,kFALSE);
   for (Int_t i=0;i<fN;i++){
@@ -1469,14 +1821,14 @@ void  AliITStrackerMI::AliITSlayer::SortClusters()
   //
   for (Int_t i=0;i<fN-1;i++){
     if (fZ[i]>fZ[i+1]){
-      printf("Bugg\n");
+      printf("Bug\n");
     }
   }
   //
   for (Int_t slice=0;slice<21;slice++)
   for (Int_t i=0;i<fN20[slice]-1;i++){
     if (fZ20[slice][i]>fZ20[slice][i+1]){
-      printf("Bugg\n");
+      printf("Bug\n");
     }
   }
 
@@ -1508,6 +1860,58 @@ Int_t AliITStrackerMI::AliITSlayer::FindClusterIndex(Float_t z) const {
   return m;
 }
 //------------------------------------------------------------------------
+Bool_t AliITStrackerMI::ComputeRoad(AliITStrackMI* track,Int_t ilayer,Int_t idet,Double_t &zmin,Double_t &zmax,Double_t &ymin,Double_t &ymax) const {
+  //--------------------------------------------------------------------
+  // This function computes the rectangular road for this track
+  //--------------------------------------------------------------------
+
+
+  AliITSdetector &det = fgLayers[ilayer].GetDetector(idet);
+  // take into account the misalignment: propagate track to misaligned detector plane
+  if (!track->Propagate(det.GetPhi(),det.GetRmisal())) return kFALSE;
+
+  Double_t dz=AliITSReconstructor::GetRecoParam()->GetNSigmaRoadZ()*
+                    TMath::Sqrt(track->GetSigmaZ2() + 
+                   AliITSReconstructor::GetRecoParam()->GetNSigmaZLayerForRoadZ()*
+                   AliITSReconstructor::GetRecoParam()->GetNSigmaZLayerForRoadZ()*
+                   AliITSReconstructor::GetRecoParam()->GetSigmaZ2(ilayer));
+  Double_t dy=AliITSReconstructor::GetRecoParam()->GetNSigmaRoadY()*
+                    TMath::Sqrt(track->GetSigmaY2() + 
+                   AliITSReconstructor::GetRecoParam()->GetNSigmaYLayerForRoadY()*
+                   AliITSReconstructor::GetRecoParam()->GetNSigmaYLayerForRoadY()*
+                   AliITSReconstructor::GetRecoParam()->GetSigmaY2(ilayer));
+      
+  // track at boundary between detectors, enlarge road
+  Double_t boundaryWidth=AliITSRecoParam::GetBoundaryWidth();
+  if ( (track->GetY()-dy < det.GetYmin()+boundaryWidth) || 
+       (track->GetY()+dy > det.GetYmax()-boundaryWidth) || 
+       (track->GetZ()-dz < det.GetZmin()+boundaryWidth) ||
+       (track->GetZ()+dz > det.GetZmax()-boundaryWidth) ) {
+    Float_t tgl = TMath::Abs(track->GetTgl());
+    if (tgl > 1.) tgl=1.;
+    Double_t deltaXNeighbDets=AliITSRecoParam::GetDeltaXNeighbDets();
+    dz = TMath::Sqrt(dz*dz+deltaXNeighbDets*deltaXNeighbDets*tgl*tgl);
+    Float_t snp = TMath::Abs(track->GetSnp());
+    if (snp > AliITSReconstructor::GetRecoParam()->GetMaxSnp()) return kFALSE;
+    dy = TMath::Sqrt(dy*dy+deltaXNeighbDets*deltaXNeighbDets*snp*snp);
+  } // boundary
+  
+  // add to the road a term (up to 2-3 mm) to deal with misalignments
+  dy = TMath::Sqrt(dy*dy + AliITSReconstructor::GetRecoParam()->GetRoadMisal()*AliITSReconstructor::GetRecoParam()->GetRoadMisal());
+  dz = TMath::Sqrt(dz*dz + AliITSReconstructor::GetRecoParam()->GetRoadMisal()*AliITSReconstructor::GetRecoParam()->GetRoadMisal());
+
+  Double_t r = fgLayers[ilayer].GetR();
+  zmin = track->GetZ() - dz; 
+  zmax = track->GetZ() + dz;
+  ymin = track->GetY() + r*det.GetPhi() - dy;
+  ymax = track->GetY() + r*det.GetPhi() + dy;
+
+  // bring track back to idead detector plane
+  if (!track->Propagate(det.GetPhi(),det.GetR())) return kFALSE;
+
+  return kTRUE;
+}
+//------------------------------------------------------------------------
 void AliITStrackerMI::AliITSlayer::
 SelectClusters(Double_t zmin,Double_t zmax,Double_t ymin, Double_t ymax) {
   //--------------------------------------------------------------------
@@ -1515,12 +1919,24 @@ SelectClusters(Double_t zmin,Double_t zmax,Double_t ymin, Double_t ymax) {
   //--------------------------------------------------------------------
  
   Double_t circle=2*TMath::Pi()*fR;
-  fYmin = ymin; fYmax =ymax;
+  fYmin = ymin; 
+  fYmax = ymax;
+  fZmin = zmin;
+  fZmax = zmax;
+  // AD
+  // enlarge road in y by maximum cluster error on this layer (3 sigma)
+  fYmin -= fNMaxSigmaCl*fMaxSigmaClY;
+  fYmax += fNMaxSigmaCl*fMaxSigmaClY;
+  fZmin -= fNMaxSigmaCl*fMaxSigmaClZ;
+  fZmax += fNMaxSigmaCl*fMaxSigmaClZ;
+
   Float_t ymiddle = (fYmin+fYmax)*0.5;
-  if (ymiddle<fYB[0]) {fYmin+=circle; fYmax+=circle;ymiddle+=circle;}
-  else{
-    if (ymiddle>fYB[1]) {fYmin-=circle; fYmax-=circle;ymiddle-=circle;}
+  if (ymiddle<fYB[0]) {
+    fYmin+=circle; fYmax+=circle; ymiddle+=circle;
+  } else if (ymiddle>fYB[1]) {
+    fYmin-=circle; fYmax-=circle; ymiddle-=circle;
   }
+  
   //
   fCurrentSlice =-1;
   // defualt take all
@@ -1568,7 +1984,7 @@ SelectClusters(Double_t zmin,Double_t zmax,Double_t ymin, Double_t ymax) {
     if (slice<0) slice=0;
     if (slice>5) slice=5;
     Bool_t isOK = (fYmin>fBy5[slice][0]&&fYmax<fBy5[slice][1]);
-    if ( isOK){
+    if (isOK) {
       fCurrentSlice=slice;
       fClustersCs = fClusters5[fCurrentSlice];
       fClusterIndexCs = fClusterIndex5[fCurrentSlice];
@@ -1578,10 +1994,12 @@ SelectClusters(Double_t zmin,Double_t zmax,Double_t ymin, Double_t ymax) {
     }
   }  
   //  
-  fI=FindClusterIndex(zmin); fZmax=zmax;
-  fImax = TMath::Min(FindClusterIndex(zmax)+1,fNcs);
-  fSkip = 0;
-  fAccepted =0;
+  fI        = FindClusterIndex(fZmin); 
+  fImax     = TMath::Min(FindClusterIndex(fZmax)+1,fNcs);
+  fSkip     = 0;
+  fAccepted = 0;
+
+  return;
 }
 //------------------------------------------------------------------------
 Int_t AliITStrackerMI::AliITSlayer::
@@ -1595,46 +2013,76 @@ FindDetectorIndex(Double_t phi, Double_t z) const {
   else                       // new geometry
     dphi = phi-fPhiOffset;
 
+
   if      (dphi <  0) dphi += 2*TMath::Pi();
   else if (dphi >= 2*TMath::Pi()) dphi -= 2*TMath::Pi();
   Int_t np=Int_t(dphi*fNladders*0.5/TMath::Pi()+0.5);
   if (np>=fNladders) np-=fNladders;
   if (np<0)          np+=fNladders;
 
+
   Double_t dz=fZOffset-z;
-  Int_t nz=Int_t(dz*(fNdetectors-1)*0.5/fZOffset+0.5);
-  if (nz>=fNdetectors) return -1;
-  if (nz<0)            return -1;
+  Double_t nnz = dz*(fNdetectors-1)*0.5/fZOffset+0.5;
+  Int_t nz = (nnz<0 ? -1 : (Int_t)nnz);
+  if (nz>=fNdetectors || nz<0) {
+    //printf("ndet %d phi %f z %f  np %d nz %d\n",fNdetectors,phi,z,np,nz);
+    return -1;
+  }
+
+  // ad hoc correction for 3rd ladder of SDD inner layer,
+  // which is reversed (rotated by pi around local y)
+  // this correction is OK only from AliITSv11Hybrid onwards
+  if (GetR()>12. && GetR()<20.) { // SDD inner
+    if(np==2) { // 3rd ladder
+      Double_t posMod252[3];
+      AliITSgeomTGeo::GetTranslation(252,posMod252);
+      // check the Z coordinate of Mod 252: if negative 
+      // (old SDD geometry in AliITSv11Hybrid)
+      // the swap of numeration whould be applied
+      if(posMod252[2]<0.){
+       nz = (fNdetectors-1) - nz;
+      } 
+    }
+  }
+  //printf("ndet %d phi %f z %f  np %d nz %d\n",fNdetectors,phi,z,np,nz);
+
 
   return np*fNdetectors + nz;
 }
 //------------------------------------------------------------------------
-const AliITSRecPoint *AliITStrackerMI::AliITSlayer::GetNextCluster(Int_t &ci){
+const AliITSRecPoint *AliITStrackerMI::AliITSlayer::GetNextCluster(Int_t &ci,Bool_t test)
+{
   //--------------------------------------------------------------------
   // This function returns clusters within the "window" 
   //--------------------------------------------------------------------
 
-  if (fCurrentSlice<0){
+  if (fCurrentSlice<0) {
     Double_t rpi2 = 2.*fR*TMath::Pi();
     for (Int_t i=fI; i<fImax; i++) {
       Double_t y = fY[i];
+      Double_t z = fZ[i];
       if (fYmax<y) y -= rpi2;
       if (fYmin>y) y += rpi2;
       if (y<fYmin) continue;
       if (y>fYmax) continue;
-      if (fClusters[i]->GetQ()==0&&fSkip==2) continue;
+      // AD
+      // skip clusters that are in "extended" road but they 
+      // 3sigma error does not touch the original road
+      if (z+fNMaxSigmaCl*TMath::Sqrt(fClusters[i]->GetSigmaZ2())<fZmin+fNMaxSigmaCl*fMaxSigmaClZ) continue;
+      if (z-fNMaxSigmaCl*TMath::Sqrt(fClusters[i]->GetSigmaZ2())>fZmax-fNMaxSigmaCl*fMaxSigmaClZ) continue;
+      //
+      if (TMath::Abs(fClusters[i]->GetQ())<1.e-13 && fSkip==2) continue;
       ci=i;
-      fI=i+1;
+      if (!test) fI=i+1;
       return fClusters[i];
     }
-  }
-  else{
+  } else {
     for (Int_t i=fI; i<fImax; i++) {
       if (fYcs[i]<fYmin) continue;
       if (fYcs[i]>fYmax) continue;
-      if (fClustersCs[i]->GetQ()==0&&fSkip==2) continue;
+      if (TMath::Abs(fClustersCs[i]->GetQ())<1.e-13 && fSkip==2) continue;
       ci=fClusterIndexCs[i];
-      fI=i+1;
+      if (!test) fI=i+1;
       return fClustersCs[i];
     }
   }
@@ -1739,6 +2187,76 @@ const {
   return d;
 }
 //------------------------------------------------------------------------
+AliITStrackerMI::AliITSdetector::AliITSdetector(const AliITSdetector& det):
+fR(det.fR),
+fRmisal(det.fRmisal),
+fPhi(det.fPhi),
+fSinPhi(det.fSinPhi),
+fCosPhi(det.fCosPhi),
+fYmin(det.fYmin),
+fYmax(det.fYmax),
+fZmin(det.fZmin),
+fZmax(det.fZmax),
+fIsBad(det.fIsBad),
+fNChips(det.fNChips),
+fChipIsBad(det.fChipIsBad)
+{
+  //Copy constructor
+}
+//------------------------------------------------------------------------
+void AliITStrackerMI::AliITSdetector::ReadBadDetectorAndChips(Int_t ilayer,Int_t idet,
+                                              const AliITSDetTypeRec *detTypeRec)
+{
+  //--------------------------------------------------------------------
+  // Read bad detectors and chips from calibration objects in AliITSDetTypeRec
+  //--------------------------------------------------------------------
+
+  // In AliITSDetTypeRec, detector numbers go from 0 to 2197
+  // while in the tracker they start from 0 for each layer
+  for(Int_t il=0; il<ilayer; il++) 
+    idet += AliITSgeomTGeo::GetNLadders(il+1)*AliITSgeomTGeo::GetNDetectors(il+1);
+
+  Int_t detType;
+  if (ilayer==0 || ilayer==1) {        // ----------  SPD
+    detType = 0;
+  } else if (ilayer==2 || ilayer==3) { // ----------  SDD
+    detType = 1;
+  } else if (ilayer==4 || ilayer==5) { // ----------  SSD
+    detType = 2;
+  } else {
+    printf("AliITStrackerMI::AliITSdetector::InitBadFromOCDB: Wrong layer number %d\n",ilayer);
+    return;
+  }
+
+  // Get calibration from AliITSDetTypeRec
+  AliITSCalibration *calib = (AliITSCalibration*)detTypeRec->GetCalibrationModel(idet);
+  calib->SetModuleIndex(idet);
+  AliITSCalibration *calibSPDdead = 0;
+  if(detType==0) calibSPDdead = (AliITSCalibration*)detTypeRec->GetSPDDeadModel(idet); // TEMPORARY
+  if (calib->IsBad() ||
+      (detType==0 && calibSPDdead->IsBad())) // TEMPORARY
+    {
+      SetBad();
+      //      printf("lay %d bad %d\n",ilayer,idet);
+    }
+
+  // Get segmentation from AliITSDetTypeRec
+  AliITSsegmentation *segm = (AliITSsegmentation*)detTypeRec->GetSegmentationModel(detType);
+
+  // Read info about bad chips
+  fNChips = segm->GetMaximumChipIndex()+1;
+  //printf("ilayer %d  detType %d idet %d fNChips %d %d  GetNumberOfChips %d\n",ilayer,detType,idet,fNChips,segm->GetMaximumChipIndex(),segm->GetNumberOfChips());
+  if(fChipIsBad) { delete [] fChipIsBad; fChipIsBad=NULL; }
+  fChipIsBad = new Bool_t[fNChips];
+  for (Int_t iCh=0;iCh<fNChips;iCh++) {
+    fChipIsBad[iCh] = calib->IsChipBad(iCh);
+    if (detType==0 && calibSPDdead->IsChipBad(iCh)) fChipIsBad[iCh] = kTRUE; // TEMPORARY
+    //if(fChipIsBad[iCh]) {printf("lay %d det %d bad chip %d\n",ilayer,idet,iCh);}
+  }
+
+  return;
+}
+//------------------------------------------------------------------------
 Double_t AliITStrackerMI::GetEffectiveThickness()
 {
   //--------------------------------------------------------------------
@@ -1777,7 +2295,7 @@ Double_t AliITStrackerMI::GetEffectiveThickness()
 }
 //------------------------------------------------------------------------
 Int_t AliITStrackerMI::AliITSlayer::InRoad() const {
-  //--------------------------------------------------------------------
+  //-------------------------------------------------------------------
   // This function returns number of clusters within the "window" 
   //--------------------------------------------------------------------
   Int_t ncl=0;
@@ -1798,266 +2316,235 @@ Int_t AliITStrackerMI::AliITSlayer::InRoad() const {
   return ncl;
 }
 //------------------------------------------------------------------------
-Bool_t AliITStrackerMI::RefitAt(Double_t xx,AliITStrackMI *t,
-                               const AliITStrackMI *c, Bool_t extra) {
+Bool_t AliITStrackerMI::RefitAt(Double_t xx,AliITStrackMI *track,
+                               const AliITStrackMI *clusters,Bool_t extra, Bool_t planeeff) 
+{
   //--------------------------------------------------------------------
-  // This function refits the track "t" at the position "x" using
-  // the clusters from "c"
+  // This function refits the track "track" at the position "x" using
+  // the clusters from "clusters"
   // If "extra"==kTRUE, 
-  //    the clusters from overlapped modules get attached to "t" 
+  //    the clusters from overlapped modules get attached to "track" 
+  // If "planeff"==kTRUE,
+  //    special approach for plane efficiency evaluation is applyed
   //--------------------------------------------------------------------
+
   Int_t index[AliITSgeomTGeo::kNLayers];
   Int_t k;
   for (k=0; k<AliITSgeomTGeo::GetNLayers(); k++) index[k]=-1;
-  Int_t nc=c->GetNumberOfClusters();
+  Int_t nc=clusters->GetNumberOfClusters();
   for (k=0; k<nc; k++) { 
-    Int_t idx=c->GetClusterIndex(k),nl=(idx&0xf0000000)>>28;
-    index[nl]=idx; 
+    Int_t idx=clusters->GetClusterIndex(k);
+    Int_t ilayer=(idx&0xf0000000)>>28;
+    index[ilayer]=idx; 
+  }
+
+  return RefitAt(xx,track,index,extra,planeeff); // call the method below
+}
+//------------------------------------------------------------------------
+Bool_t AliITStrackerMI::RefitAt(Double_t xx,AliITStrackMI *track,
+                               const Int_t *clusters,Bool_t extra, Bool_t planeeff) 
+{
+  //--------------------------------------------------------------------
+  // This function refits the track "track" at the position "x" using
+  // the clusters from array
+  // If "extra"==kTRUE, 
+  //    the clusters from overlapped modules get attached to "track" 
+  // If "planeff"==kTRUE,
+  //    special approach for plane efficiency evaluation is applyed
+  //--------------------------------------------------------------------
+  Int_t index[AliITSgeomTGeo::kNLayers];
+  Int_t k;
+  for (k=0; k<AliITSgeomTGeo::GetNLayers(); k++) index[k]=-1;
+  //
+  for (k=0; k<AliITSgeomTGeo::GetNLayers(); k++) { 
+    index[k]=clusters[k]; 
+  }
+
+  // special for cosmics and TPC prolonged tracks: 
+  // propagate to the innermost of:
+  // - innermost layer crossed by the track
+  // - innermost layer where a cluster was associated to the track
+  static AliITSRecoParam *repa = NULL;
+  if(!repa){
+    repa = (AliITSRecoParam*) AliITSReconstructor::GetRecoParam();
+    if(!repa){
+      repa = AliITSRecoParam::GetHighFluxParam();
+      AliWarning("Using default AliITSRecoParam class");
+    }
   }
+  Int_t evsp=repa->GetEventSpecie();
+  ULong_t trStatus=0;
+  if(track->GetESDtrack()) trStatus=track->GetStatus();
+  Int_t innermostlayer=0;
+  if((evsp&AliRecoParam::kCosmic) || (trStatus&AliESDtrack::kTPCin))  {
+    innermostlayer=5;
+    Double_t drphi = TMath::Abs(track->GetD(0.,0.));
+    for(innermostlayer=0; innermostlayer<AliITSgeomTGeo::GetNLayers(); innermostlayer++) {
+      if( (drphi < (fgLayers[innermostlayer].GetR()+1.)) ||
+         index[innermostlayer] >= 0 ) break;
+    }
 
-  // special for cosmics: check which the innermost layer crossed
-  // by the track
-  Int_t innermostlayer=5;
-  Double_t d = TMath::Abs(t->GetD(0.,0.));
-  for(innermostlayer=0; innermostlayer<AliITSgeomTGeo::GetNLayers(); innermostlayer++)
-    if(d<fgLayers[innermostlayer].GetR()) break;
-  //printf(" d  %f  innermost %d\n",d,innermostlayer);
+    AliDebug(2,Form(" drphi  %f  innermost %d",drphi,innermostlayer));
+  }
 
+  Int_t modstatus=1; // found
+  Float_t xloc,zloc;
   Int_t from, to, step;
-  if (xx > t->GetX()) {
+  if (xx > track->GetX()) {
       from=innermostlayer; to=AliITSgeomTGeo::GetNLayers();
       step=+1;
   } else {
       from=AliITSgeomTGeo::GetNLayers()-1; to=innermostlayer-1;
       step=-1;
   }
-  TString dir=(step>0 ? "outward" : "inward");
+  TString dir = (step>0 ? "outward" : "inward");
 
-  // loop on the layers
-  for (Int_t i=from; i != to; i += step) {
-     AliITSlayer &layer=fgLayers[i];
+  for (Int_t ilayer = from; ilayer != to; ilayer += step) {
+     AliITSlayer &layer=fgLayers[ilayer];
      Double_t r=layer.GetR();
+
+     if (step<0 && xx>r) break;
+
      // material between SSD and SDD, SDD and SPD
-     Double_t hI=i-0.5*step; 
+     Double_t hI=ilayer-0.5*step; 
      if (TMath::Abs(hI-3.5)<0.01) // SDDouter
-       if(!CorrectForShieldMaterial(t,"SDD",dir)) return kFALSE;
+       if(!CorrectForShieldMaterial(track,"SDD",dir)) return kFALSE;
      if (TMath::Abs(hI-1.5)<0.01) // SPDouter
-       if(!CorrectForShieldMaterial(t,"SPD",dir)) return kFALSE;
-     
-     // remember old position [SR, GSI 18.02.2003]
-     Double_t oldX=0., oldY=0., oldZ=0.;
-     if (t->IsStartedTimeIntegral() && step==1) {
-        t->GetGlobalXYZat(t->GetX(),oldX,oldY,oldZ);
-     }
-     //
+       if(!CorrectForShieldMaterial(track,"SPD",dir)) return kFALSE;
+
 
      Double_t oldGlobXYZ[3];
-     t->GetXYZ(oldGlobXYZ);
+     if (!track->GetXYZ(oldGlobXYZ)) return kFALSE;
+
+     // continue if we are already beyond this layer
+     Double_t oldGlobR = TMath::Sqrt(oldGlobXYZ[0]*oldGlobXYZ[0]+oldGlobXYZ[1]*oldGlobXYZ[1]);
+     if(step>0 && oldGlobR > r) continue; // going outward
+     if(step<0 && oldGlobR < r) continue; // going inward
 
      Double_t phi,z;
-     if (!t->GetPhiZat(r,phi,z)) return kFALSE;
+     if (!track->GetPhiZat(r,phi,z)) return kFALSE;
 
      Int_t idet=layer.FindDetectorIndex(phi,z);
+
+     // check if we allow a prolongation without point for large-eta tracks
+     Int_t skip = CheckSkipLayer(track,ilayer,idet);
+     if (skip==2) {
+       modstatus = 4; // out in z
+       if(LocalModuleCoord(ilayer,idet,track,xloc,zloc)) { // local module coords
+        track->SetModuleIndexInfo(ilayer,idet,modstatus,xloc,zloc);
+       }
+       // cross layer
+       // apply correction for material of the current layer
+       // add time if going outward
+       CorrectForLayerMaterial(track,ilayer,oldGlobXYZ,dir);
+       continue;
+     }
+
      if (idet<0) return kFALSE;
 
+
      const AliITSdetector &det=layer.GetDetector(idet);
-     phi=det.GetPhi();
-     if (!t->Propagate(phi,det.GetR())) return kFALSE;
-     t->SetDetectorIndex(idet);
+     // only for ITS-SA tracks refit
+     if (ilayer>1 && fTrackingPhase.Contains("RefitInward") && !(track->GetStatus()&AliESDtrack::kTPCin)) track->SetCheckInvariant(kFALSE);
+     // 
+     if (!track->Propagate(det.GetPhi(),det.GetR())) return kFALSE;
 
-     const AliITSRecPoint *cl=0;
-     Double_t maxchi2=1000.*AliITSReconstructor::GetRecoParam()->GetMaxChi2();
+     track->SetDetectorIndex(idet);
+     if(!LocalModuleCoord(ilayer,idet,track,xloc,zloc)) return kFALSE; // local module coords
 
-     Int_t idx=index[i];
-     if (idx>=0) {
-        const AliITSRecPoint *c=(AliITSRecPoint *)GetCluster(idx); 
-       if (c){
-         if (idet != c->GetDetectorIndex()) {
-           idet=c->GetDetectorIndex();
-           const AliITSdetector &det=layer.GetDetector(idet);
-           if (!t->Propagate(det.GetPhi(),det.GetR())) {
-             return kFALSE;
-           }
-           t->SetDetectorIndex(idet);
-         }
-         //Double_t chi2=t->GetPredictedChi2(c);
-         Int_t layer = (idx & 0xf0000000) >> 28;;
-         Double_t chi2=GetPredictedChi2MI(t,c,layer);
-         if (chi2<maxchi2) { 
-           cl=c; 
-           maxchi2=chi2; 
-         } else {
-           return kFALSE;
-         }
-       }
-     }
+     Double_t dz,zmin,zmax,dy,ymin,ymax;
 
-     if (cl) {
-       if (!UpdateMI(t,cl,maxchi2,idx)) return kFALSE;
-       t->SetSampledEdx(cl->GetQ(),t->GetNumberOfClusters()-1);
-     }
+     const AliITSRecPoint *clAcc=0;
+     Double_t maxchi2=1000.*AliITSReconstructor::GetRecoParam()->GetMaxChi2();
 
-     if (extra) { //search for extra clusters
-        AliITStrackV2 tmp(*t);
-        Double_t dz=4*TMath::Sqrt(tmp.GetSigmaZ2()+AliITSReconstructor::GetRecoParam()->GetSigmaZ2(i));
-        if (dz < 0.5*TMath::Abs(tmp.GetTgl())) dz=0.5*TMath::Abs(tmp.GetTgl());
-        Double_t dy=4*TMath::Sqrt(t->GetSigmaY2()+AliITSReconstructor::GetRecoParam()->GetSigmaY2(i));
-        if (dy < 0.5*TMath::Abs(tmp.GetSnp())) dy=0.5*TMath::Abs(tmp.GetSnp());
-        Double_t zmin=t->GetZ() - dz;
-        Double_t zmax=t->GetZ() + dz;
-        Double_t ymin=t->GetY() + phi*r - dy;
-        Double_t ymax=t->GetY() + phi*r + dy;
-        layer.SelectClusters(zmin,zmax,ymin,ymax);
-
-        const AliITSRecPoint *c=0; Int_t ci=-1,cci=-1;
-        Double_t maxchi2=1000.*AliITSReconstructor::GetRecoParam()->GetMaxChi2(), tolerance=0.1;
-        while ((c=layer.GetNextCluster(ci))!=0) {
-           if (idet == c->GetDetectorIndex()) continue;
-
-          const AliITSdetector &det=layer.GetDetector(c->GetDetectorIndex());
-
-          if (!tmp.Propagate(det.GetPhi(),det.GetR())) continue;
-           
-          if (TMath::Abs(tmp.GetZ() - c->GetZ()) > tolerance) continue;
-           if (TMath::Abs(tmp.GetY() - c->GetY()) > tolerance) continue;
-
-           Double_t chi2=tmp.GetPredictedChi2(c);
-           if (chi2<maxchi2) { maxchi2=chi2; cci=ci; }
-        }
-        if (cci>=0) t->SetExtraCluster(i,(i<<28)+cci);
+     Int_t idx=index[ilayer];
+     if (idx>=0) { // cluster in this layer
+       modstatus = 6; // no refit
+       const AliITSRecPoint *cl=(AliITSRecPoint *)GetCluster(idx); 
+       if (cl) {
+        if (idet != cl->GetDetectorIndex()) {
+          idet=cl->GetDetectorIndex();
+          const AliITSdetector &detc=layer.GetDetector(idet);
+          if (!track->Propagate(detc.GetPhi(),detc.GetR())) return kFALSE;
+          track->SetDetectorIndex(idet);
+          if(!LocalModuleCoord(ilayer,idet,track,xloc,zloc)) return kFALSE; // local module coords
+        }
+        Int_t cllayer = (idx & 0xf0000000) >> 28;;
+        Double_t chi2=GetPredictedChi2MI(track,cl,cllayer);
+        if (chi2<maxchi2) { 
+          clAcc=cl; 
+          maxchi2=chi2; 
+          modstatus = 1; // found
+        } else {
+           return kFALSE; //
+        }
+       }
+     } else { // no cluster in this layer
+       if (skip==1) {
+        modstatus = 3; // skipped
+         // Plane Eff determination:
+         if (planeeff && ilayer==AliITSReconstructor::GetRecoParam()->GetIPlanePlaneEff()) {
+           if (IsOKForPlaneEff(track,clusters,ilayer))  // only adequate track for plane eff. evaluation
+              UseTrackForPlaneEff(track,ilayer);
+         }
+       } else {
+        modstatus = 5; // no cls in road
+        // check dead
+        if (!ComputeRoad(track,ilayer,idet,zmin,zmax,ymin,ymax)) return kFALSE;
+        dz = 0.5*(zmax-zmin);
+        dy = 0.5*(ymax-ymin);
+        Int_t dead = CheckDeadZone(track,ilayer,idet,dz,dy,kTRUE);
+        if (dead==1) modstatus = 7; // holes in z in SPD
+        if (dead==2 || dead==3 || dead==4) modstatus = 2; // dead from OCDB
+       }
      }
-
-     // track time update [SR, GSI 17.02.2003]
-     if (t->IsStartedTimeIntegral() && step==1) {
-        Double_t newX, newY, newZ;
-        t->GetGlobalXYZat(t->GetX(),newX,newY,newZ);
-        Double_t dL2 = (oldX-newX)*(oldX-newX) + (oldY-newY)*(oldY-newY) + 
-                       (oldZ-newZ)*(oldZ-newZ);
-        t->AddTimeStep(TMath::Sqrt(dL2));
+     
+     if (clAcc) {
+       if (!UpdateMI(track,clAcc,maxchi2,idx)) return kFALSE;
+       track->SetSampledEdx(clAcc->GetQ(),ilayer-2);
      }
-     //
-
-     // Correct for material of the current layer
-     if(!CorrectForLayerMaterial(t,i,oldGlobXYZ,dir)) return kFALSE;
-
-  } // end loop on the layers
-
-  if (!t->PropagateTo(xx,0.,0.)) return kFALSE;
-  return kTRUE;
-}
-//------------------------------------------------------------------------
-Bool_t 
-AliITStrackerMI::RefitAt(Double_t xx,AliITStrackMI *t,const Int_t *clindex) {
-  //--------------------------------------------------------------------
-  // This function refits the track "t" at the position "x" using
-  // the clusters from array
-  //--------------------------------------------------------------------
-  Int_t index[AliITSgeomTGeo::kNLayers];
-  Int_t k;
-  for (k=0; k<AliITSgeomTGeo::GetNLayers(); k++) index[k]=-1;
-  //
-  for (k=0; k<AliITSgeomTGeo::GetNLayers(); k++) { 
-    index[k]=clindex[k]; 
-  }
-
-  // special for cosmics: check which the innermost layer crossed
-  // by the track
-  Int_t innermostlayer=5;
-  Double_t d = TMath::Abs(t->GetD(0.,0.));
-  for(innermostlayer=0; innermostlayer<AliITSgeomTGeo::GetNLayers(); innermostlayer++)
-    if(d<fgLayers[innermostlayer].GetR()) break;
-  //printf(" d  %f  innermost %d\n",d,innermostlayer);
-
-  Int_t from, to, step;
-  if (xx > t->GetX()) {
-      from=innermostlayer; to=AliITSgeomTGeo::GetNLayers();
-      step=+1;
-  } else {
-      from=AliITSgeomTGeo::GetNLayers()-1; to=innermostlayer-1;
-      step=-1;
-  }
-  TString dir=(step>0 ? "outward" : "inward");
-
-  for (Int_t i=from; i != to; i += step) {
-     AliITSlayer &layer=fgLayers[i];
-     Double_t r=layer.GetR();
-     if (step<0 && xx>r) break;
-
-     // material between SSD and SDD, SDD and SPD
-     Double_t hI=i-0.5*step; 
-     if (TMath::Abs(hI-3.5)<0.01) // SDDouter
-       if(!CorrectForShieldMaterial(t,"SDD",dir)) return kFALSE;
-     if (TMath::Abs(hI-1.5)<0.01) // SPDouter
-       if(!CorrectForShieldMaterial(t,"SPD",dir)) return kFALSE;
-
-     // remember old position [SR, GSI 18.02.2003]
-     Double_t oldX=0., oldY=0., oldZ=0.;
-     if (t->IsStartedTimeIntegral() && step==1) {
-        t->GetGlobalXYZat(t->GetX(),oldX,oldY,oldZ);
-     }
-     //
-     Double_t oldGlobXYZ[3];
-     t->GetXYZ(oldGlobXYZ);
-
-     Double_t phi,z;
-     if (!t->GetPhiZat(r,phi,z)) return kFALSE;
-
-     Int_t idet=layer.FindDetectorIndex(phi,z);
-     if (idet<0) return kFALSE;
-     const AliITSdetector &det=layer.GetDetector(idet);
-     phi=det.GetPhi();
-     if (!t->Propagate(phi,det.GetR())) return kFALSE;
-     t->SetDetectorIndex(idet);
-
-     const AliITSRecPoint *cl=0;
-     Double_t maxchi2=1000.*AliITSReconstructor::GetRecoParam()->GetMaxChi2();
-
-     Int_t idx=index[i];
-     if (idx>=0) {
-        const AliITSRecPoint *c=(AliITSRecPoint *)GetCluster(idx); 
-       if (c){
-         if (idet != c->GetDetectorIndex()) {
-           idet=c->GetDetectorIndex();
-           const AliITSdetector &det=layer.GetDetector(idet);
-           if (!t->Propagate(det.GetPhi(),det.GetR())) {
-             return kFALSE;
-           }
-           t->SetDetectorIndex(idet);
-         }
-         //Double_t chi2=t->GetPredictedChi2(c);
-         Int_t layer = (idx & 0xf0000000) >> 28;;
-         Double_t chi2=GetPredictedChi2MI(t,c,layer);
-         if (chi2<maxchi2) { 
-           cl=c; 
-           maxchi2=chi2; 
-         } else {
-           return kFALSE;
-         }
-       }
-     }
-
-     if (cl) {
-       if (!UpdateMI(t,cl,maxchi2,idx)) return kFALSE;
-       t->SetSampledEdx(cl->GetQ(),t->GetNumberOfClusters()-1);
-     }
-
+     track->SetModuleIndexInfo(ilayer,idet,modstatus,xloc,zloc);
+
+
+     if (extra && clAcc) { // search for extra clusters in overlapped modules
+       AliITStrackV2 tmp(*track);
+       if (!ComputeRoad(track,ilayer,idet,zmin,zmax,ymin,ymax)) return kFALSE;
+       layer.SelectClusters(zmin,zmax,ymin,ymax);
+       
+       const AliITSRecPoint *clExtra=0; Int_t ci=-1,cci=-1;
+       Int_t idetExtra=-1;  
+       maxchi2=1000.*AliITSReconstructor::GetRecoParam()->GetMaxChi2();
+       Double_t tolerance=0.1;
+       while ((clExtra=layer.GetNextCluster(ci))!=0) {
+        // only clusters in another module! (overlaps)
+        idetExtra = clExtra->GetDetectorIndex();
+        if (idet == idetExtra) continue;
+        
+        const AliITSdetector &detx=layer.GetDetector(idetExtra);
+        
+        if (!tmp.Propagate(detx.GetPhi(),detx.GetR()+clExtra->GetX())) continue;
+        if (TMath::Abs(tmp.GetZ() - clExtra->GetZ()) > tolerance) continue;
+        if (TMath::Abs(tmp.GetY() - clExtra->GetY()) > tolerance) continue;
+        if (!tmp.Propagate(detx.GetPhi(),detx.GetR())) continue;
+        
+        Double_t chi2=tmp.GetPredictedChi2(clExtra);
+        if (chi2<maxchi2) { maxchi2=chi2; cci=ci; }
+       }
+       if (cci>=0) {
+        track->SetExtraCluster(ilayer,(ilayer<<28)+cci);
+        track->SetExtraModule(ilayer,idetExtra);
+       }
+     } // end search for extra clusters in overlapped modules
+     
      // Correct for material of the current layer
-     if(!CorrectForLayerMaterial(t,i,oldGlobXYZ,dir)) return kFALSE;
-                 
-     // track time update [SR, GSI 17.02.2003]
-     if (t->IsStartedTimeIntegral() && step==1) {
-        Double_t newX, newY, newZ;
-        t->GetGlobalXYZat(t->GetX(),newX,newY,newZ);
-        Double_t dL2 = (oldX-newX)*(oldX-newX) + (oldY-newY)*(oldY-newY) + 
-                       (oldZ-newZ)*(oldZ-newZ);
-        t->AddTimeStep(TMath::Sqrt(dL2));
-     }
-     //
+     // cross material
+     // add time if going outward
+     if(!CorrectForLayerMaterial(track,ilayer,oldGlobXYZ,dir)) return kFALSE;
+     track->SetCheckInvariant(kTRUE);
+  } // end loop on layers
 
-  }
+  if (!track->PropagateTo(xx,0.,0.)) return kFALSE;
 
-  if (!t->PropagateTo(xx,0.,0.)) return kFALSE;
   return kTRUE;
 }
 //------------------------------------------------------------------------
@@ -2074,7 +2561,7 @@ Double_t AliITStrackerMI::GetNormalizedChi2(AliITStrackMI * track, Int_t mode)
   Float_t *ny = GetNy(fCurrentEsdTrack), *nz = GetNz(fCurrentEsdTrack); 
   if (mode<100){
     for (Int_t i = 0;i<6;i++){
-      if (track->GetClIndex(i)>0){
+      if (track->GetClIndex(i)>=0){
        Float_t cerry, cerrz;
        if (ny[i]>0) {cerry = erry[i]; cerrz=errz[i];}
        else 
@@ -2106,7 +2593,7 @@ Double_t AliITStrackerMI::GetNormalizedChi2(AliITStrackMI * track, Int_t mode)
   }
   else{
     for (Int_t i = 0;i<4;i++){
-      if (track->GetClIndex(i)>0){
+      if (track->GetClIndex(i)>=0){
        Float_t cerry, cerrz;
        if (ny[i]>0) {cerry = erry[i]; cerrz=errz[i];}
        else { cerry= track->GetSigmaY(i); cerrz = track->GetSigmaZ(i);}
@@ -2118,7 +2605,7 @@ Double_t AliITStrackerMI::GetNormalizedChi2(AliITStrackMI * track, Int_t mode)
       }
     }
     for (Int_t i = 4;i<6;i++){
-      if (track->GetClIndex(i)>0){     
+      if (track->GetClIndex(i)>=0){    
        Float_t cerry, cerrz;
        if (ny[i]>0) {cerry = erry[i]; cerrz=errz[i];}
        else { cerry= track->GetSigmaY(i); cerrz = track->GetSigmaZ(i);}
@@ -2155,20 +2642,43 @@ Double_t AliITStrackerMI::GetNormalizedChi2(AliITStrackMI * track, Int_t mode)
     }
   }
   if (match<0) match=0;
-  Float_t deadzonefactor = (track->GetNDeadZone()>0) ? 3*(1.1-track->GetDeadZoneProbability()):0.;
+
+  // penalty factor for missing points (NDeadZone>0), but no penalty
+  // for layer with deadZoneProb close to 1 (either we wanted to skip layer
+  // or there is a dead from OCDB)
+  Float_t deadzonefactor = 0.; 
+  if (track->GetNDeadZone()>0.) {    
+    Int_t sumDeadZoneProbability=0; 
+    for(Int_t ilay=0;ilay<6;ilay++) {
+      if(track->GetDeadZoneProbability(ilay)>0.) sumDeadZoneProbability++;
+    }
+    Int_t nDeadZoneWithProbNot1=(Int_t)(track->GetNDeadZone())-sumDeadZoneProbability;
+    if(nDeadZoneWithProbNot1>0) {
+      Float_t deadZoneProbability = track->GetNDeadZone()-(Float_t)sumDeadZoneProbability;
+      AliDebug(2,Form("nDeadZone %f sumDZProbability %d nDZWithProbNot1 %d deadZoneProb %f\n",track->GetNDeadZone(),sumDeadZoneProbability,nDeadZoneWithProbNot1,deadZoneProbability));
+      deadZoneProbability /= (Float_t)nDeadZoneWithProbNot1;
+      Float_t one = 1.;
+      deadZoneProbability = TMath::Min(deadZoneProbability,one);
+      deadzonefactor = 3.*(1.1-deadZoneProbability);  
+    }
+  }  
+
   Double_t normchi2 = 2*track->GetNSkipped()+match+deadzonefactor+(1+(2*track->GetNSkipped()+deadzonefactor)/track->GetNumberOfClusters())*
     (chi2)/TMath::Max(double(sum-track->GetNSkipped()),
                                1./(1.+track->GetNSkipped()));     
- return normchi2;
+  AliDebug(2,Form("match %f deadzonefactor %f chi2 %f sum %f skipped %f\n",match,deadzonefactor,chi2,sum,track->GetNSkipped()));
+  AliDebug(2,Form("NormChi2 %f  cls %d\n",normchi2,track->GetNumberOfClusters()));
+  return normchi2;
 }
 //------------------------------------------------------------------------
-Double_t AliITStrackerMI::GetMatchingChi2(AliITStrackMI * track1, AliITStrackMI * track2)
+Double_t AliITStrackerMI::GetMatchingChi2(const AliITStrackMI * track1,const AliITStrackMI * track2)
 {
   //
   // return matching chi2 between two tracks
+  Double_t largeChi2=1000.;
+
   AliITStrackMI track3(*track2);
-  track3.Propagate(track1->GetAlpha(),track1->GetX());
+  if (!track3.Propagate(track1->GetAlpha(),track1->GetX())) return largeChi2;
   TMatrixD vec(5,1);
   vec(0,0)=track1->GetY()   - track3.GetY();
   vec(1,0)=track1->GetZ()   - track3.GetZ();
@@ -2203,39 +2713,55 @@ Double_t AliITStrackerMI::GetMatchingChi2(AliITStrackMI * track1, AliITStrackMI
   return chi2(0,0);
 }
 //------------------------------------------------------------------------
-Double_t  AliITStrackerMI::GetDeadZoneProbability(Double_t zpos, Double_t zerr)
+Double_t  AliITStrackerMI::GetSPDDeadZoneProbability(Double_t zpos, Double_t zerr) const
 {
   //
   //  return probability that given point (characterized by z position and error) 
   //  is in SPD dead zone
+  //     This method assumes that fSPDdetzcentre is ordered from -z to +z
   //
   Double_t probability = 0.;
-  Double_t absz = TMath::Abs(zpos);
-  Double_t nearestz = (absz<2.) ? 0.5*(fSPDdetzcentre[1]+fSPDdetzcentre[2]) : 
-                                  0.5*(fSPDdetzcentre[2]+fSPDdetzcentre[3]);
-  if (TMath::Abs(absz-nearestz)>0.25+3.*zerr) return probability;
+  Double_t nearestz = 0.,distz=0.;
+  Int_t    nearestzone = -1;
+  Double_t mindistz = 1000.;
+
+  // find closest dead zone
+  for (Int_t i=0; i<3; i++) {
+    distz=TMath::Abs(zpos-0.5*(fSPDdetzcentre[i]+fSPDdetzcentre[i+1]));
+    if (distz<mindistz) {
+      nearestzone=i;
+      nearestz=0.5*(fSPDdetzcentre[i]+fSPDdetzcentre[i+1]);
+      mindistz=distz;
+    }
+  }
+
+  // too far from dead zone
+  if (TMath::Abs(zpos-nearestz)>0.25+3.*zerr) return probability;
+
+
   Double_t zmin, zmax;   
-  if (zpos<-6.) { // dead zone at z = -7
+  if (nearestzone==0) { // dead zone at z = -7
     zmin = fSPDdetzcentre[0] + 0.5*AliITSRecoParam::GetSPDdetzlength();
     zmax = fSPDdetzcentre[1] - 0.5*AliITSRecoParam::GetSPDdetzlength();
-  } else if (zpos>6.) { // dead zone at z = +7
-    zmin = fSPDdetzcentre[2] + 0.5*AliITSRecoParam::GetSPDdetzlength();
-    zmax = fSPDdetzcentre[3] - 0.5*AliITSRecoParam::GetSPDdetzlength();
-  } else if (absz<2.) { // dead zone at z = 0
+  } else if (nearestzone==1) { // dead zone at z = 0
     zmin = fSPDdetzcentre[1] + 0.5*AliITSRecoParam::GetSPDdetzlength();
     zmax = fSPDdetzcentre[2] - 0.5*AliITSRecoParam::GetSPDdetzlength();
+  } else if (nearestzone==2) { // dead zone at z = +7
+    zmin = fSPDdetzcentre[2] + 0.5*AliITSRecoParam::GetSPDdetzlength();
+    zmax = fSPDdetzcentre[3] - 0.5*AliITSRecoParam::GetSPDdetzlength();
   } else {
     zmin = 0.;
     zmax = 0.;
   }
   // probability that the true z is in the range [zmin,zmax] (i.e. inside 
   // dead zone)
-  probability = 0.5*( TMath::Erf((zpos-zmin)/zerr/TMath::Sqrt(2.)) - 
-                     TMath::Erf((zpos-zmax)/zerr/TMath::Sqrt(2.)) );
+  probability = 0.5*( AliMathBase::ErfFast((zpos-zmin)/zerr/TMath::Sqrt(2.)) - 
+                     AliMathBase::ErfFast((zpos-zmax)/zerr/TMath::Sqrt(2.)) );
+  AliDebug(2,Form("zpos %f +- %f nearestzone %d  zmin zmax %f %f prob %f\n",zpos,zerr,nearestzone,zmin,zmax,probability));
   return probability;
 }
 //------------------------------------------------------------------------
-Double_t AliITStrackerMI::GetTruncatedChi2(AliITStrackMI * track, Float_t fac)
+Double_t AliITStrackerMI::GetTruncatedChi2(const AliITStrackMI * track, Float_t fac)
 {
   //
   // calculate normalized chi2
@@ -2263,7 +2789,7 @@ Double_t AliITStrackerMI::GetTruncatedChi2(AliITStrackMI * track, Float_t fac)
   return normchi2;
 }
 //------------------------------------------------------------------------
-Double_t AliITStrackerMI::GetInterpolatedChi2(AliITStrackMI * forwardtrack, AliITStrackMI * backtrack)
+Double_t AliITStrackerMI::GetInterpolatedChi2(const AliITStrackMI * forwardtrack,const AliITStrackMI * backtrack)
 {
   //
   // calculate normalized chi2
@@ -2304,7 +2830,7 @@ Float_t  *AliITStrackerMI::GetWeight(Int_t index) {
   return fgLayers[l].GetWeight(c);
 }
 //------------------------------------------------------------------------
-void AliITStrackerMI::RegisterClusterTracks(AliITStrackMI* track,Int_t id)
+void AliITStrackerMI::RegisterClusterTracks(const AliITStrackMI* track,Int_t id)
 {
   //---------------------------------------------
   // register track to the list
@@ -2326,7 +2852,7 @@ void AliITStrackerMI::RegisterClusterTracks(AliITStrackMI* track,Int_t id)
   }
 }
 //------------------------------------------------------------------------
-void AliITStrackerMI::UnRegisterClusterTracks(AliITStrackMI* track, Int_t id)
+void AliITStrackerMI::UnRegisterClusterTracks(const AliITStrackMI* track, Int_t id)
 {
   //---------------------------------------------
   // unregister track from the list
@@ -2359,9 +2885,9 @@ Float_t AliITStrackerMI::GetNumberOfSharedClusters(AliITStrackMI* track,Int_t id
     Int_t l=(index & 0xf0000000) >> 28;
     Int_t c=(index & 0x0fffffff) >> 00;
     if (c>fgLayers[l].GetNumberOfClusters()) continue;
-    if (ny[l]==0){
-      printf("problem\n");
-    }
+    // if (ny[l]<1.e-13){
+    //   printf("problem\n");
+    // }
     AliITSRecPoint *cl = (AliITSRecPoint*)GetCluster(index);
     Float_t weight=1;
     //
@@ -2382,6 +2908,7 @@ Float_t AliITStrackerMI::GetNumberOfSharedClusters(AliITStrackMI* track,Int_t id
       if (fgLayers[l].GetClusterTracks(itrack,c)>=0 && fgLayers[l].GetClusterTracks(itrack,c)!=id){
        list[l]=index;
        clist[l] = (AliITSRecPoint*)GetCluster(index);
+       track->SetSharedWeight(l,weight);
        shared+=weight; 
        break;
       }
@@ -2391,7 +2918,7 @@ Float_t AliITStrackerMI::GetNumberOfSharedClusters(AliITStrackMI* track,Int_t id
   return shared;
 }
 //------------------------------------------------------------------------
-Int_t AliITStrackerMI::GetOverlapTrack(AliITStrackMI *track, Int_t trackID, Int_t &shared, Int_t clusterlist[6],Int_t overlist[6])
+Int_t AliITStrackerMI::GetOverlapTrack(const AliITStrackMI *track, Int_t trackID, Int_t &shared, Int_t clusterlist[6],Int_t overlist[6])
 {
   //
   // find first shared track 
@@ -2409,9 +2936,9 @@ Int_t AliITStrackerMI::GetOverlapTrack(AliITStrackMI *track, Int_t trackID, Int_
     Int_t index = clusterlist[icluster];
     Int_t l=(index & 0xf0000000) >> 28;
     Int_t c=(index & 0x0fffffff) >> 00;
-    if (ny[l]==0){
-      printf("problem\n");
-    }
+    // if (ny[l]<1.e-13){
+    //   printf("problem\n");
+    // }
     if (c>fgLayers[l].GetNumberOfClusters()) continue;
     //if (l>3) continue;
     AliITSRecPoint *cl = (AliITSRecPoint*)GetCluster(index);
@@ -2443,13 +2970,13 @@ Int_t AliITStrackerMI::GetOverlapTrack(AliITStrackMI *track, Int_t trackID, Int_
     if (trackindex==2) sharedtrack =TMath::Min(tracks[0],tracks[1]);
     else{
       //
-      Int_t track[24], cluster[24];
-      for (Int_t i=0;i<trackindex;i++){ track[i]=-1; cluster[i]=0;}
+      Int_t tracks2[24], cluster[24];
+      for (Int_t i=0;i<trackindex;i++){ tracks2[i]=-1; cluster[i]=0;}
       Int_t index =0;
       //
       for (Int_t i=0;i<trackindex;i++){
        if (tracks[i]<0) continue;
-       track[index] = tracks[i];
+       tracks2[index] = tracks[i];
        cluster[index]++;       
        for (Int_t j=i+1;j<trackindex;j++){
          if (tracks[j]<0) continue;
@@ -2463,7 +2990,7 @@ Int_t AliITStrackerMI::GetOverlapTrack(AliITStrackMI *track, Int_t trackID, Int_
       Int_t max=0;
       for (Int_t i=0;i<index;i++){
        if (cluster[index]>max) {
-         sharedtrack=track[index];
+         sharedtrack=tracks2[index];
          max=cluster[index];
        }
       }
@@ -2610,8 +3137,6 @@ AliITStrackMI *  AliITStrackerMI::GetBest2Tracks(Int_t trackID1, Int_t trackID2,
       //if (track2->fFakeRatio>0) continue;
       Float_t nskipped=0;            
       RegisterClusterTracks(track2,trackID2);
-      Int_t list1[6],list2[6];
-      AliITSRecPoint *clist1[6], *clist2[6] ;
       Float_t cconflict1 = GetNumberOfSharedClusters(track1,trackID1,list1,clist1);
       Float_t cconflict2 = GetNumberOfSharedClusters(track2,trackID2,list2,clist2);
       UnRegisterClusterTracks(track2,trackID2);
@@ -2667,7 +3192,7 @@ AliITStrackMI *  AliITStrackerMI::GetBest2Tracks(Int_t trackID1, Int_t trackID2,
          }       
        }
        //
-       Double_t chi21=0,chi22=0;
+       chi21=0;chi22=0;
        if (TMath::Abs(track1->GetDy(i))>0.) {
          chi21 = (track1->GetDy(i)/track1->GetSigmaY(i))*(track1->GetDy(i)/track1->GetSigmaY(i))+
            (track1->GetDz(i)/track1->GetSigmaZ(i))*(track1->GetDz(i)/track1->GetSigmaZ(i));
@@ -2770,7 +3295,8 @@ void AliITStrackerMI::AddTrackHypothesys(AliITStrackMI * track, Int_t esdindex)
   // add track to the list of hypothesys
   //------------------------------------------------------------------
 
-  if (esdindex>=fTrackHypothesys.GetEntriesFast()) fTrackHypothesys.Expand(esdindex*2+10);
+  if (esdindex>=fTrackHypothesys.GetEntriesFast()) 
+    fTrackHypothesys.Expand(TMath::Max(fTrackHypothesys.GetSize(),esdindex*2+10));
   //
   TObjArray * array = (TObjArray*) fTrackHypothesys.At(esdindex);
   if (!array) {
@@ -2827,12 +3353,12 @@ void AliITStrackerMI::SortTrackHypothesys(Int_t esdindex, Int_t maxcut, Int_t mo
   //take errors of best track as a reference
   Float_t *erry = GetErrY(esdindex), *errz = GetErrZ(esdindex);
   Float_t *ny = GetNy(esdindex), *nz = GetNz(esdindex);
-  for (Int_t i=0;i<6;i++) {
-    if (besttrack->GetClIndex(i)>0){
-      erry[i] = besttrack->GetSigmaY(i); erry[i+6] = besttrack->GetSigmaY(i+6);
-      errz[i] = besttrack->GetSigmaZ(i); errz[i+6] = besttrack->GetSigmaZ(i+6);
-      ny[i]   = besttrack->GetNy(i);
-      nz[i]   = besttrack->GetNz(i);
+  for (Int_t j=0;j<6;j++) {
+    if (besttrack->GetClIndex(j)>=0){
+      erry[j] = besttrack->GetSigmaY(j); erry[j+6] = besttrack->GetSigmaY(j+6);
+      errz[j] = besttrack->GetSigmaZ(j); errz[j+6] = besttrack->GetSigmaZ(j+6);
+      ny[j]   = besttrack->GetNy(j);
+      nz[j]   = besttrack->GetNz(j);
     }
   }
   //
@@ -2844,6 +3370,7 @@ void AliITStrackerMI::SortTrackHypothesys(Int_t esdindex, Int_t maxcut, Int_t mo
   for (Int_t itrack=0;itrack<entries;itrack++){
     AliITStrackMI * track = (AliITStrackMI*)array->At(itrack);
     if (track){
+      AliDebug(2,Form("track %d  ncls %d\n",itrack,track->GetNumberOfClusters()));
       track->SetChi2MIP(0,GetNormalizedChi2(track, mode));            
       if (track->GetChi2MIP(0)<AliITSReconstructor::GetRecoParam()->GetMaxChi2PerCluster(0)) 
        chi2[itrack] = track->GetChi2MIP(0);
@@ -2857,13 +3384,14 @@ void AliITStrackerMI::SortTrackHypothesys(Int_t esdindex, Int_t maxcut, Int_t mo
   //
   TMath::Sort(entries,chi2,index,kFALSE);
   besttrack = (AliITStrackMI*)array->At(index[0]);
+  if(besttrack) AliDebug(2,Form("ncls best track %d\n",besttrack->GetNumberOfClusters()));
   if (besttrack&&besttrack->GetChi2MIP(0)<AliITSReconstructor::GetRecoParam()->GetMaxChi2PerCluster(0)){
-    for (Int_t i=0;i<6;i++){
-      if (besttrack->GetClIndex(i)>0){
-       erry[i] = besttrack->GetSigmaY(i); erry[i+6] = besttrack->GetSigmaY(i+6);
-       errz[i] = besttrack->GetSigmaZ(i); erry[i+6] = besttrack->GetSigmaY(i+6);
-       ny[i]   = besttrack->GetNy(i);
-       nz[i]   = besttrack->GetNz(i);
+    for (Int_t j=0;j<6;j++){
+      if (besttrack->GetClIndex(j)>=0){
+       erry[j] = besttrack->GetSigmaY(j); erry[j+6] = besttrack->GetSigmaY(j+6);
+       errz[j] = besttrack->GetSigmaZ(j); erry[j+6] = besttrack->GetSigmaY(j+6);
+       ny[j]   = besttrack->GetNy(j);
+       nz[j]   = besttrack->GetNz(j);
       }
     }
   }
@@ -2873,7 +3401,8 @@ void AliITStrackerMI::SortTrackHypothesys(Int_t esdindex, Int_t maxcut, Int_t mo
   for (Int_t itrack=0;itrack<entries;itrack++){
     AliITStrackMI * track = (AliITStrackMI*)array->At(itrack);
     if (track){      
-      track->SetChi2MIP(0,GetNormalizedChi2(track,mode));            
+      track->SetChi2MIP(0,GetNormalizedChi2(track,mode));
+      AliDebug(2,Form("track %d  ncls %d\n",itrack,track->GetNumberOfClusters()));            
       if (track->GetChi2MIP(0)<AliITSReconstructor::GetRecoParam()->GetMaxChi2PerCluster(0)) 
        chi2[itrack] = track->GetChi2MIP(0)-0*(track->GetNumberOfClusters()+track->GetNDeadZone()); 
       else
@@ -2892,17 +3421,18 @@ void AliITStrackerMI::SortTrackHypothesys(Int_t esdindex, Int_t maxcut, Int_t mo
     TMath::Sort(entries,chi2,index,kFALSE);
     besttrack = (AliITStrackMI*)array->At(index[0]);
     if (besttrack){
+      AliDebug(2,Form("ncls best track %d     %f   %f\n",besttrack->GetNumberOfClusters(),besttrack->GetChi2MIP(0),chi2[index[0]]));
       //
-      for (Int_t i=0;i<6;i++){
-       if (besttrack->GetNz(i)>0&&besttrack->GetNy(i)>0){
-         erry[i] = besttrack->GetSigmaY(i); erry[i+6] = besttrack->GetSigmaY(i+6);
-         errz[i] = besttrack->GetSigmaZ(i); errz[i+6] = besttrack->GetSigmaZ(i+6);
-         ny[i]   = besttrack->GetNy(i);
-         nz[i]   = besttrack->GetNz(i);
+      for (Int_t j=0;j<6;j++){
+       if (besttrack->GetNz(j)>0&&besttrack->GetNy(j)>0){
+         erry[j] = besttrack->GetSigmaY(j); erry[j+6] = besttrack->GetSigmaY(j+6);
+         errz[j] = besttrack->GetSigmaZ(j); errz[j+6] = besttrack->GetSigmaZ(j+6);
+         ny[j]   = besttrack->GetNy(j);
+         nz[j]   = besttrack->GetNz(j);
        }
       }
       besttrack->SetChi2MIP(0,GetNormalizedChi2(besttrack,mode));
-      Float_t minchi2 = TMath::Min(besttrack->GetChi2MIP(0)+5.+besttrack->GetNUsed(), double(AliITSReconstructor::GetRecoParam()->GetMaxChi2PerCluster(0)));
+      minchi2 = TMath::Min(besttrack->GetChi2MIP(0)+5.+besttrack->GetNUsed(), double(AliITSReconstructor::GetRecoParam()->GetMaxChi2PerCluster(0)));
       Float_t minn = besttrack->GetNumberOfClusters()-3;
       Int_t accepted=0;
       for (Int_t i=0;i<entries;i++){
@@ -2921,12 +3451,12 @@ void AliITStrackerMI::SortTrackHypothesys(Int_t esdindex, Int_t maxcut, Int_t mo
          if (!shortbest) accepted++;
          //
          newarray->AddLast(array->RemoveAt(index[i]));      
-         for (Int_t i=0;i<6;i++){
-           if (nz[i]==0){
-             erry[i] = track->GetSigmaY(i); erry[i+6] = track->GetSigmaY(i+6);
-             errz[i] = track->GetSigmaZ(i); errz[i]   = track->GetSigmaZ(i+6);
-             ny[i]   = track->GetNy(i);
-             nz[i]   = track->GetNz(i);
+         for (Int_t j=0;j<6;j++){
+           if (nz[j]==0){
+             erry[j] = track->GetSigmaY(j); erry[j+6] = track->GetSigmaY(j+6);
+             errz[j] = track->GetSigmaZ(j); errz[j]   = track->GetSigmaZ(j+6);
+             ny[j]   = track->GetNy(j);
+             nz[j]   = track->GetNz(j);
            }
          }
        }
@@ -2982,7 +3512,9 @@ AliITStrackMI * AliITStrackerMI::GetBestHypothesys(Int_t esdindex, AliITStrackMI
     backtrack = new(backtrack) AliITStrackMI(*track); 
     if (track->GetConstrain()) {
       if (!CorrectForPipeMaterial(backtrack,"inward")) continue;
-      if (!backtrack->Improve(0,xyzVtx,ersVtx))         continue;     
+      if (AliITSReconstructor::GetRecoParam()->GetImproveWithVertex()) {
+       if (!backtrack->Improve(0,xyzVtx,ersVtx)) continue;     
+      }
       backtrack->ResetCovariance(10.);      
     }else{
       backtrack->ResetCovariance(10.);
@@ -3049,9 +3581,13 @@ AliITStrackMI * AliITStrackerMI::GetBestHypothesys(Int_t esdindex, AliITStrackMI
   }
   delete backtrack;
   delete forwardtrack;
+
+  if (!besttrack)  return 0;
+
   Int_t accepted=0;
   for (Int_t i=0;i<entries;i++){    
-    AliITStrackMI * track = (AliITStrackMI*)array->At(i);   
+    AliITStrackMI * track = (AliITStrackMI*)array->At(i);
+   
     if (!track) continue;
     
     if (accepted>checkmax || track->GetChi2MIP(3)>AliITSReconstructor::GetRecoParam()->GetMaxChi2PerCluster(3)*6. || 
@@ -3069,6 +3605,7 @@ AliITStrackMI * AliITStrackerMI::GetBestHypothesys(Int_t esdindex, AliITStrackMI
   //
   array->Compress();
   SortTrackHypothesys(esdindex,checkmax,1);
+
   array = (TObjArray*) fTrackHypothesys.At(esdindex);
   if (!array) return 0; // PH What can be the reason? Check SortTrackHypothesys
   besttrack = (AliITStrackMI*)array->At(0);  
@@ -3079,7 +3616,7 @@ AliITStrackMI * AliITStrackerMI::GetBestHypothesys(Int_t esdindex, AliITStrackMI
   AliITStrackMI *longtrack =0;
   minchi2 =1000;
   Float_t minn=besttrack->GetNumberOfClusters()+besttrack->GetNDeadZone();
-  for (Int_t itrack=entries-1;itrack>0;itrack--){
+  for (Int_t itrack=entries-1;itrack>0;itrack--) {
     AliITStrackMI * track = (AliITStrackMI*)array->At(itrack);
     if (!track->GetConstrain()) continue;
     if (track->GetNumberOfClusters()+track->GetNDeadZone()<minn) continue;
@@ -3128,7 +3665,7 @@ AliITStrackMI * AliITStrackerMI::GetBestHypothesys(Int_t esdindex, AliITStrackMI
     Float_t *ny = GetNy(esdindex), *nz = GetNz(esdindex);
     for (Int_t i=0;i<6;i++){
       Int_t index = besttrack->GetClIndex(i);
-      if (index<=0) continue; 
+      if (index<0) continue; 
       Int_t ilayer =  (index & 0xf0000000) >> 28;
       if (besttrack->GetSigmaY(ilayer)<0.00000000001) continue;
       AliITSRecPoint *c = (AliITSRecPoint*)GetCluster(index);     
@@ -3145,7 +3682,7 @@ AliITStrackMI * AliITStrackerMI::GetBestHypothesys(Int_t esdindex, AliITStrackMI
        AliITStrackMI * track = (AliITStrackMI*)array->At(i);   
        if (!track) continue;
        if (track->GetChi2MIP(0)>besttrack->GetChi2MIP(0)+2.*shared+1.) break;
-       if ( (track->GetClIndex(ilayer)>0) && (track->GetClIndex(ilayer)!=besttrack->GetClIndex(ilayer))){
+       if ( (track->GetClIndex(ilayer)>=0) && (track->GetClIndex(ilayer)!=besttrack->GetClIndex(ilayer))){
          cansign = kFALSE;
          break;
        }
@@ -3178,23 +3715,23 @@ void  AliITStrackerMI::GetBestHypothesysMIP(TObjArray &itsTracks)
     Float_t minn=0;
     Float_t maxchi2=1000;
     for (Int_t j=0;j<array->GetEntriesFast();j++){
-      AliITStrackMI* track = (AliITStrackMI*)array->At(j);
-      if (!track) continue;
-      if (track->GetGoldV0()) {
-       longtrack = track;   //gold V0 track taken
+      AliITStrackMI* trackHyp = (AliITStrackMI*)array->At(j);
+      if (!trackHyp) continue;
+      if (trackHyp->GetGoldV0()) {
+       longtrack = trackHyp;   //gold V0 track taken
        break;
       }
-      if (track->GetNumberOfClusters()+track->GetNDeadZone()<minn) continue;
-      Float_t chi2 = track->GetChi2MIP(0);
+      if (trackHyp->GetNumberOfClusters()+trackHyp->GetNDeadZone()<minn) continue;
+      Float_t chi2 = trackHyp->GetChi2MIP(0);
       if (fAfterV0){
-       if (!track->GetGoldV0()&&track->GetConstrain()==kFALSE) chi2+=5;
+       if (!trackHyp->GetGoldV0()&&trackHyp->GetConstrain()==kFALSE) chi2+=5;
       }
-      if (track->GetNumberOfClusters()+track->GetNDeadZone()>minn) maxchi2 = track->GetChi2MIP(0);       
+      if (trackHyp->GetNumberOfClusters()+trackHyp->GetNDeadZone()>minn) maxchi2 = trackHyp->GetChi2MIP(0);       
       //
       if (chi2 > maxchi2) continue;
-      minn= track->GetNumberOfClusters()+track->GetNDeadZone();
+      minn= trackHyp->GetNumberOfClusters()+trackHyp->GetNDeadZone();
       maxchi2 = chi2;
-      longtrack=track;
+      longtrack=trackHyp;
     }    
     //
     //
@@ -3225,13 +3762,13 @@ void  AliITStrackerMI::GetBestHypothesysMIP(TObjArray &itsTracks)
       if (besttrack&&fAfterV0) {
        UpdateESDtrack(besttrack,AliESDtrack::kITSin);
       }
-      if (besttrack&&fConstraint[fPass]) 
-       UpdateESDtrack(besttrack,AliESDtrack::kITSin);
-      if (besttrack->GetChi2MIP(0)+besttrack->GetNUsed()>1.5 && fConstraint[fPass]) {
-       if ( TMath::Abs(besttrack->GetD(0))>0.1 || 
-            TMath::Abs(besttrack->GetD(1))>0.1 ) track->SetReconstructed(kFALSE);      
-      }       
-
+      if (besttrack) {
+       if (fConstraint[fPass]) UpdateESDtrack(besttrack,AliESDtrack::kITSin);
+       if (besttrack->GetChi2MIP(0)+besttrack->GetNUsed()>1.5 && fConstraint[fPass]) {
+         if ( TMath::Abs(besttrack->GetD(0))>0.1 || 
+              TMath::Abs(besttrack->GetD(1))>0.1 ) track->SetReconstructed(kFALSE);    
+       }       
+      }
     }    
   }
 } 
@@ -3242,8 +3779,11 @@ void AliITStrackerMI::CookLabel(AliITStrackMI *track,Float_t wrong) const {
   //--------------------------------------------------------------------
   Int_t tpcLabel=-1; 
      
-  if ( track->GetESDtrack())   tpcLabel =  TMath::Abs(track->GetESDtrack()->GetTPCLabel());
-
+  if (track->GetESDtrack()){
+    tpcLabel = track->GetESDtrack()->GetTPCLabel();
+    ULong_t trStatus=track->GetESDtrack()->GetStatus();
+    if(!(trStatus&AliESDtrack::kTPCin)) tpcLabel=track->GetLabel(); // for ITSsa tracks
+  }
    track->SetChi2MIP(9,0);
    Int_t nwrong=0;
    for (Int_t i=0;i<track->GetNumberOfClusters();i++){
@@ -3252,8 +3792,8 @@ void AliITStrackerMI::CookLabel(AliITStrackMI *track,Float_t wrong) const {
      AliITSRecPoint *cl = (AliITSRecPoint*)GetCluster(cindex);
      Int_t isWrong=1;
      for (Int_t ind=0;ind<3;ind++){
-       if (tpcLabel>0)
-        if (cl->GetLabel(ind)==tpcLabel) isWrong=0;
+       if (cl->GetLabel(ind)==TMath::Abs(tpcLabel)) isWrong=0;
+       //AliDebug(2,Form("icl %d  ilab %d lab %d",i,ind,cl->GetLabel(ind)));
      }
      track->SetChi2MIP(9,track->GetChi2MIP(9)+isWrong*(2<<l));
      nwrong+=isWrong;
@@ -3261,23 +3801,19 @@ void AliITStrackerMI::CookLabel(AliITStrackMI *track,Float_t wrong) const {
    Int_t nclusters = track->GetNumberOfClusters();
    if (nclusters > 0) //PH Some tracks don't have any cluster
      track->SetFakeRatio(double(nwrong)/double(nclusters));
-   if (tpcLabel>0){
-     if (track->GetFakeRatio()>wrong) track->SetLabel(-tpcLabel);
-     else
-       track->SetLabel(tpcLabel);
+   if (tpcLabel>0 && track->GetFakeRatio()>wrong) {
+     track->SetLabel(-tpcLabel);
+   } else {
+     track->SetLabel(tpcLabel);
    }
+   AliDebug(2,Form(" nls %d wrong %d  label %d  tpcLabel %d\n",nclusters,nwrong,track->GetLabel(),tpcLabel));
    
 }
 //------------------------------------------------------------------------
-void AliITStrackerMI::CookdEdx(AliITStrackMI* track)
-{
+void AliITStrackerMI::CookdEdx(AliITStrackMI* track){
   //
+  // Fill the dE/dx in this track
   //
-  //  Int_t list[6];
-  //AliITSRecPoint * clist[6];
-  //  Int_t shared = GetNumberOfSharedClusters(track,index,list,clist);
-  Float_t dedx[4];
-  Int_t accepted=0;
   track->SetChi2MIP(9,0);
   for (Int_t i=0;i<track->GetNumberOfClusters();i++){
     Int_t cindex = track->GetClusterIndex(i);
@@ -3289,37 +3825,15 @@ void AliITStrackerMI::CookdEdx(AliITStrackMI* track)
       if (cl->GetLabel(ind)==lab) isWrong=0;
     }
     track->SetChi2MIP(9,track->GetChi2MIP(9)+isWrong*(2<<l));
-    if (l<2) continue;
-    //if (l>3 && (cl->GetNy()>4) || (cl->GetNz()>4)) continue;  //shared track
-    //if (l>3&& !(cl->GetType()==1||cl->GetType()==10)) continue;
-    //if (l<4&& !(cl->GetType()==1)) continue;   
-    dedx[accepted]= track->GetSampledEdx(i);
-    //dedx[accepted]= track->fNormQ[l];
-    accepted++;
-  }
-  if (accepted<1) {
-    track->SetdEdx(0);
-    return;
   }
-  Int_t indexes[4];
-  TMath::Sort(accepted,dedx,indexes,kFALSE);
   Double_t low=0.;
   Double_t up=0.51;    
-  Double_t nl=low*accepted, nu =up*accepted;  
-  Float_t sumamp = 0;
-  Float_t sumweight =0;
-  for (Int_t i=0; i<accepted; i++) {
-    Float_t weight =1;
-    if (i<nl+0.1)     weight = TMath::Max(1.-(nl-i),0.);
-    if (i>nu-1)     weight = TMath::Max(nu-i,0.);
-    sumamp+= dedx[indexes[i]]*weight;
-    sumweight+=weight;
-  }
-  track->SetdEdx(sumamp/sumweight);
+  track->CookdEdx(low,up);
 }
 //------------------------------------------------------------------------
 void AliITStrackerMI::MakeCoefficients(Int_t ntracks){
   //
+  // Create some arrays
   //
   if (fCoefficients) delete []fCoefficients;
   fCoefficients = new Float_t[ntracks*48];
@@ -3329,14 +3843,22 @@ void AliITStrackerMI::MakeCoefficients(Int_t ntracks){
 Double_t AliITStrackerMI::GetPredictedChi2MI(AliITStrackMI* track, const AliITSRecPoint *cluster,Int_t layer) 
 {
   //
+  // Compute predicted chi2
   //
-  //
-  Float_t erry,errz;
+  // Take into account the mis-alignment (bring track to cluster plane)
+  Double_t xTrOrig=track->GetX();
+  if (!track->Propagate(xTrOrig+cluster->GetX())) return 1000.;
+  Float_t erry,errz,covyz;
   Float_t theta = track->GetTgl();
   Float_t phi   = track->GetSnp();
-  phi = TMath::Sqrt(phi*phi/(1.-phi*phi));
-  AliITSClusterParam::GetError(layer,cluster,theta,phi,track->GetExpQ(),erry,errz);
-  Double_t chi2 = track->GetPredictedChi2MI(cluster->GetY(),cluster->GetZ(),erry,errz);
+  phi *= TMath::Sqrt(1./((1.-phi)*(1.+phi)));
+  AliITSClusterParam::GetError(layer,cluster,theta,phi,track->GetExpQ(),erry,errz,covyz);
+  AliDebug(2,Form(" chi2: tr-cl   %f  %f   tr X %f cl X %f",track->GetY()-cluster->GetY(),track->GetZ()-cluster->GetZ(),track->GetX(),cluster->GetX()));
+  AliDebug(2,Form(" chi2: tr-cl   %f  %f   tr X %f cl X %f",track->GetY()-cluster->GetY(),track->GetZ()-cluster->GetZ(),track->GetX(),cluster->GetX()));
+  Double_t chi2 = track->GetPredictedChi2MI(cluster->GetY(),cluster->GetZ(),erry,errz,covyz);
+  // Bring the track back to detector plane in ideal geometry
+  // [mis-alignment will be accounted for in UpdateMI()]
+  if (!track->Propagate(xTrOrig)) return 1000.;
   Float_t ny,nz;
   AliITSClusterParam::GetNTeor(layer,cluster,theta,phi,ny,nz);  
   Double_t delta = cluster->GetNy()+cluster->GetNz()-nz-ny;
@@ -3349,8 +3871,9 @@ Double_t AliITStrackerMI::GetPredictedChi2MI(AliITStrackMI* track, const AliITSR
   track->SetNz(layer,nz);
   track->SetSigmaY(layer,erry);
   track->SetSigmaZ(layer, errz);
+  track->SetSigmaYZ(layer,covyz);
   //track->fNormQ[layer] = cluster->GetQ()/TMath::Sqrt(1+theta*theta+phi*phi);
-  track->SetNormQ(layer,cluster->GetQ()/TMath::Sqrt((1.+ track->GetTgl()*track->GetTgl())/(1.- track->GetSnp()*track->GetSnp())));
+  track->SetNormQ(layer,cluster->GetQ()/TMath::Sqrt((1.+ track->GetTgl()*track->GetTgl())/((1.-track->GetSnp())*(1.+track->GetSnp()))));
   return chi2;
 
 }
@@ -3358,7 +3881,7 @@ Double_t AliITStrackerMI::GetPredictedChi2MI(AliITStrackMI* track, const AliITSR
 Int_t AliITStrackerMI::UpdateMI(AliITStrackMI* track, const AliITSRecPoint* cl,Double_t chi2,Int_t index) const 
 {
   //
-  //
+  // Update ITS track
   //
   Int_t layer = (index & 0xf0000000) >> 28;
   track->SetClIndex(layer, index);
@@ -3369,36 +3892,53 @@ Int_t AliITStrackerMI::UpdateMI(AliITStrackMI* track, const AliITSRecPoint* cl,D
     }
   }
 
-  if (cl->GetQ()<=0) return 0;  // ingore the "virtual" clusters
+  if (TMath::Abs(cl->GetQ())<1.e-13) return 0;  // ingore the "virtual" clusters
 
-  //Float_t clxyz[3]; cl->GetGlobalXYZ(clxyz);Double_t trxyz[3]; track->GetXYZ(trxyz);printf("gtr %f %f %f\n",trxyz[0],trxyz[1],trxyz[2]);printf("gcl %f %f %f\n",clxyz[0],clxyz[1],clxyz[2]);
 
+  // Take into account the mis-alignment (bring track to cluster plane)
+  Double_t xTrOrig=track->GetX();
+  Float_t clxyz[3]; cl->GetGlobalXYZ(clxyz);Double_t trxyz[3]; track->GetXYZ(trxyz);
+  AliDebug(2,Form("gtr %f %f %f",trxyz[0],trxyz[1],trxyz[2]));
+  AliDebug(2,Form("gcl %f %f %f",clxyz[0],clxyz[1],clxyz[2]));
+  AliDebug(2,Form(" xtr %f  xcl %f",track->GetX(),cl->GetX()));
 
-  // Take into account the mis-alignment
-  Double_t x=track->GetX()+cl->GetX();
-  if (!track->PropagateTo(x,0.,0.)) return 0;
+  if (!track->Propagate(xTrOrig+cl->GetX())) return 0;
   
-  return track->UpdateMI(cl->GetY(),cl->GetZ(),track->GetSigmaY(layer),track->GetSigmaZ(layer),chi2,index);
+  AliCluster c(*cl);
+  c.SetSigmaY2(track->GetSigmaY(layer)*track->GetSigmaY(layer));
+  c.SetSigmaZ2(track->GetSigmaZ(layer)*track->GetSigmaZ(layer));
+  c.SetSigmaYZ(track->GetSigmaYZ(layer));
+
+
+  Int_t updated = track->UpdateMI(&c,chi2,index);
+  // Bring the track back to detector plane in ideal geometry
+  if (!track->Propagate(xTrOrig)) return 0;
+  if(!updated) AliDebug(2,"update failed");
+  return updated;
 }
+
 //------------------------------------------------------------------------
-void AliITStrackerMI::GetDCASigma(AliITStrackMI* track, Float_t & sigmarfi, Float_t &sigmaz)
+void AliITStrackerMI::GetDCASigma(const AliITStrackMI* track, Float_t & sigmarfi, Float_t &sigmaz)
 {
   //
   //DCA sigmas parameterization
   //to be paramterized using external parameters in future 
   //
   // 
-  sigmarfi = 0.0040+1.4 *TMath::Abs(track->GetC())+332.*track->GetC()*track->GetC();
-  sigmaz   = 0.0110+4.37*TMath::Abs(track->GetC());
+  Double_t curv=track->GetC();
+  sigmarfi = 0.0040+1.4 *TMath::Abs(curv)+332.*curv*curv;
+  sigmaz   = 0.0110+4.37*TMath::Abs(curv);
 }
 //------------------------------------------------------------------------
-void AliITStrackerMI::SignDeltas( TObjArray *ClusterArray, Float_t vz)
+void AliITStrackerMI::SignDeltas(const TObjArray *clusterArray, Float_t vz)
 {
   //
+  // Clusters from delta electrons?
   //  
-  Int_t entries = ClusterArray->GetEntriesFast();
+  Int_t entries = clusterArray->GetEntriesFast();
   if (entries<4) return;
-  AliITSRecPoint* cluster = (AliITSRecPoint*)ClusterArray->At(0);
+  AliITSRecPoint* cluster = (AliITSRecPoint*)clusterArray->At(0);
   Int_t layer = cluster->GetLayer();
   if (layer>1) return;
   Int_t index[10000];
@@ -3406,7 +3946,7 @@ void AliITStrackerMI::SignDeltas( TObjArray *ClusterArray, Float_t vz)
   Float_t r = (layer>0)? 7:4;
   // 
   for (Int_t i=0;i<entries;i++){
-    AliITSRecPoint* cl0 = (AliITSRecPoint*)ClusterArray->At(i);
+    AliITSRecPoint* cl0 = (AliITSRecPoint*)clusterArray->At(i);
     Float_t nz = 1+TMath::Abs((cl0->GetZ()-vz)/r);
     if (cl0->GetNy()+cl0->GetNz()<=5+2*layer+nz) continue;
     index[ncandidates] = i;  //candidate to belong to delta electron track
@@ -3419,7 +3959,7 @@ void AliITStrackerMI::SignDeltas( TObjArray *ClusterArray, Float_t vz)
   //  
   //
   for (Int_t i=0;i<ncandidates;i++){
-    AliITSRecPoint* cl0 = (AliITSRecPoint*)ClusterArray->At(index[i]);
+    AliITSRecPoint* cl0 = (AliITSRecPoint*)clusterArray->At(index[i]);
     if (cl0->GetDeltaProbability()>0.8) continue;
     // 
     Int_t ncl = 0;
@@ -3427,7 +3967,7 @@ void AliITStrackerMI::SignDeltas( TObjArray *ClusterArray, Float_t vz)
     sumy=sumz=sumy2=sumyz=sumw=0.0;
     for (Int_t j=0;j<ncandidates;j++){
       if (i==j) continue;
-      AliITSRecPoint* cl1 = (AliITSRecPoint*)ClusterArray->At(index[j]);
+      AliITSRecPoint* cl1 = (AliITSRecPoint*)clusterArray->At(index[j]);
       //
       Float_t dz = cl0->GetZ()-cl1->GetZ();
       Float_t dy = cl0->GetY()-cl1->GetY();
@@ -3464,19 +4004,20 @@ void AliITStrackerMI::SignDeltas( TObjArray *ClusterArray, Float_t vz)
 void AliITStrackerMI::UpdateESDtrack(AliITStrackMI* track, ULong_t flags) const
 {
   //
+  // Update ESD track
   //
   track->UpdateESDtrack(flags);
   AliITStrackMI * oldtrack = (AliITStrackMI*)(track->GetESDtrack()->GetITStrack());
   if (oldtrack) delete oldtrack; 
   track->GetESDtrack()->SetITStrack(new AliITStrackMI(*track));
-  if (TMath::Abs(track->GetDnorm(1))<0.000000001){
-    printf("Problem\n");
-  }
+  // if (TMath::Abs(track->GetDnorm(1))<0.000000001){
+  //   printf("Problem\n");
+  // }
 }
 //------------------------------------------------------------------------
 Int_t AliITStrackerMI::GetNearestLayer(const Double_t *xr) const{
   //
-  //Get nearest upper layer close to the point xr.
+  // Get nearest upper layer close to the point xr.
   // rough approximation 
   //
   const Float_t kRadiuses[6]={4,6.5,15.03,24.,38.5,43.7};
@@ -3491,825 +4032,6 @@ Int_t AliITStrackerMI::GetNearestLayer(const Double_t *xr) const{
   return res;
 }
 //------------------------------------------------------------------------
-void AliITStrackerMI::UpdateTPCV0(AliESDEvent *event){
-  //
-  //try to update, or reject TPC  V0s
-  //
-  Int_t nv0s = event->GetNumberOfV0s();
-  Int_t nitstracks = fTrackHypothesys.GetEntriesFast();
-
-  for (Int_t i=0;i<nv0s;i++){
-    AliESDv0 * vertex = event->GetV0(i);
-    Int_t ip = vertex->GetIndex(0);
-    Int_t im = vertex->GetIndex(1);
-    //
-    TObjArray * arrayp = (ip<nitstracks) ? (TObjArray*)fTrackHypothesys.At(ip):0;
-    TObjArray * arraym = (im<nitstracks) ? (TObjArray*)fTrackHypothesys.At(im):0;
-    AliITStrackMI * trackp = (arrayp!=0) ? (AliITStrackMI*)arrayp->At(0):0;
-    AliITStrackMI * trackm = (arraym!=0) ? (AliITStrackMI*)arraym->At(0):0;
-    //
-    //
-    if (trackp){
-      if (trackp->GetNumberOfClusters()+trackp->GetNDeadZone()>5.5){
-       if (trackp->GetConstrain()&&trackp->GetChi2MIP(0)<3) vertex->SetStatus(-100);
-       if (!trackp->GetConstrain()&&trackp->GetChi2MIP(0)<2) vertex->SetStatus(-100); 
-      }
-    }
-
-    if (trackm){
-      if (trackm->GetNumberOfClusters()+trackm->GetNDeadZone()>5.5){
-       if (trackm->GetConstrain()&&trackm->GetChi2MIP(0)<3) vertex->SetStatus(-100);
-       if (!trackm->GetConstrain()&&trackm->GetChi2MIP(0)<2) vertex->SetStatus(-100); 
-      }
-    }
-    if (vertex->GetStatus()==-100) continue;
-    //
-    Double_t xrp[3]; vertex->GetXYZ(xrp[0],xrp[1],xrp[2]);  //I.B.
-    Int_t clayer = GetNearestLayer(xrp);                    //I.B.
-    vertex->SetNBefore(clayer);        //
-    vertex->SetChi2Before(9*clayer);   //
-    vertex->SetNAfter(6-clayer);       //
-    vertex->SetChi2After(0);           //
-    //
-    if (clayer >1 ){ // calculate chi2 before vertex
-      Float_t chi2p = 0, chi2m=0;  
-      //
-      if (trackp){
-       for (Int_t ilayer=0;ilayer<clayer;ilayer++){
-         if (trackp->GetClIndex(ilayer)>0){
-           chi2p+=trackp->GetDy(ilayer)*trackp->GetDy(ilayer)/(trackp->GetSigmaY(ilayer)*trackp->GetSigmaY(ilayer))+
-             trackp->GetDz(ilayer)*trackp->GetDz(ilayer)/(trackp->GetSigmaZ(ilayer)*trackp->GetSigmaZ(ilayer));
-         }
-         else{
-           chi2p+=9;
-         }
-       }
-      }else{
-       chi2p = 9*clayer;
-      }
-      //
-      if (trackm){
-       for (Int_t ilayer=0;ilayer<clayer;ilayer++){
-         if (trackm->GetClIndex(ilayer)>0){
-           chi2m+=trackm->GetDy(ilayer)*trackm->GetDy(ilayer)/(trackm->GetSigmaY(ilayer)*trackm->GetSigmaY(ilayer))+
-             trackm->GetDz(ilayer)*trackm->GetDz(ilayer)/(trackm->GetSigmaZ(ilayer)*trackm->GetSigmaZ(ilayer));
-         }
-         else{
-           chi2m+=9;
-         }
-       }
-      }else{
-       chi2m = 9*clayer;
-      }
-      vertex->SetChi2Before(TMath::Min(chi2p,chi2m));
-      if (TMath::Min(chi2p,chi2m)/Float_t(clayer)<4) vertex->SetStatus(-10);  // track exist before vertex
-    }
-    
-    if (clayer < 5 ){ // calculate chi2 after vertex
-      Float_t chi2p = 0, chi2m=0;  
-      //
-      if (trackp&&TMath::Abs(trackp->GetTgl())<1.){
-       for (Int_t ilayer=clayer;ilayer<6;ilayer++){
-         if (trackp->GetClIndex(ilayer)>0){
-           chi2p+=trackp->GetDy(ilayer)*trackp->GetDy(ilayer)/(trackp->GetSigmaY(ilayer)*trackp->GetSigmaY(ilayer))+
-             trackp->GetDz(ilayer)*trackp->GetDz(ilayer)/(trackp->GetSigmaZ(ilayer)*trackp->GetSigmaZ(ilayer));
-         }
-         else{
-           chi2p+=9;
-         }
-       }
-      }else{
-       chi2p = 0;
-      }
-      //
-      if (trackm&&TMath::Abs(trackm->GetTgl())<1.){
-       for (Int_t ilayer=clayer;ilayer<6;ilayer++){
-         if (trackm->GetClIndex(ilayer)>0){
-           chi2m+=trackm->GetDy(ilayer)*trackm->GetDy(ilayer)/(trackm->GetSigmaY(ilayer)*trackm->GetSigmaY(ilayer))+
-             trackm->GetDz(ilayer)*trackm->GetDz(ilayer)/(trackm->GetSigmaZ(ilayer)*trackm->GetSigmaZ(ilayer));
-         }
-         else{
-           chi2m+=9;
-         }
-       }
-      }else{
-       chi2m = 0;
-      }
-      vertex->SetChi2After(TMath::Max(chi2p,chi2m));
-      if (TMath::Max(chi2m,chi2p)/Float_t(6-clayer)>9) vertex->SetStatus(-20);  // track not found in ITS
-    }
-  }
-  //
-}
-//------------------------------------------------------------------------
-void AliITStrackerMI::FindV02(AliESDEvent *event)
-{
-  //
-  // V0 finder
-  //
-  //  Cuts on DCA -  R dependent
-  //          max distance DCA between 2 tracks cut 
-  //          maxDist = TMath::Min(kMaxDist,kMaxDist0+pvertex->GetRr()*kMaxDist);
-  //
-  const Float_t kMaxDist0      = 0.1;    
-  const Float_t kMaxDist1      = 0.1;     
-  const Float_t kMaxDist       = 1;
-  const Float_t kMinPointAngle  = 0.85;
-  const Float_t kMinPointAngle2 = 0.99;
-  const Float_t kMinR           = 0.5;
-  const Float_t kMaxR           = 220;
-  //const Float_t kCausality0Cut   = 0.19;
-  //const Float_t kLikelihood01Cut = 0.25;
-  //const Float_t kPointAngleCut   = 0.9996;
-  const Float_t kCausality0Cut   = 0.19;
-  const Float_t kLikelihood01Cut = 0.45;
-  const Float_t kLikelihood1Cut  = 0.5;
-  const Float_t kCombinedCut     = 0.55;
-
-  //
-  //
-  TTreeSRedirector &cstream = *fDebugStreamer;
-  Int_t ntracks    = event->GetNumberOfTracks(); 
-  Int_t nitstracks = fTrackHypothesys.GetEntriesFast();
-  fOriginal.Expand(ntracks);
-  fTrackHypothesys.Expand(ntracks);
-  fBestHypothesys.Expand(ntracks);
-  //
-  AliHelix * helixes   = new AliHelix[ntracks+2];
-  TObjArray trackarray(ntracks+2);     //array with tracks - with vertex constrain
-  TObjArray trackarrayc(ntracks+2);    //array of "best    tracks" - without vertex constrain
-  TObjArray trackarrayl(ntracks+2);    //array of "longest tracks" - without vertex constrain
-  Bool_t * forbidden   = new Bool_t [ntracks+2];
-  Int_t   *itsmap      = new Int_t  [ntracks+2];
-  Float_t *dist        = new Float_t[ntracks+2];
-  Float_t *normdist0   = new Float_t[ntracks+2];
-  Float_t *normdist1   = new Float_t[ntracks+2];
-  Float_t *normdist    = new Float_t[ntracks+2];
-  Float_t *norm        = new Float_t[ntracks+2];
-  Float_t *maxr        = new Float_t[ntracks+2];
-  Float_t *minr        = new Float_t[ntracks+2];
-  Float_t *minPointAngle= new Float_t[ntracks+2];
-  //
-  AliV0 *pvertex      = new AliV0;
-  AliITStrackMI * dummy= new AliITStrackMI;
-  dummy->SetLabel(0);
-  AliITStrackMI  trackat0;    //temporary track for DCA calculation
-  //
-  Float_t primvertex[3]={GetX(),GetY(),GetZ()};
-  //
-  // make ITS -  ESD map
-  //
-  for (Int_t itrack=0;itrack<ntracks+2;itrack++) {
-    itsmap[itrack]        = -1;
-    forbidden[itrack]     = kFALSE;
-    maxr[itrack]          = kMaxR;
-    minr[itrack]          = kMinR;
-    minPointAngle[itrack] = kMinPointAngle;
-  }
-  for (Int_t itrack=0;itrack<nitstracks;itrack++){
-    AliITStrackMI * original =   (AliITStrackMI*)(fOriginal.At(itrack));
-    Int_t           esdindex =   original->GetESDtrack()->GetID();
-    itsmap[esdindex]         =   itrack;
-  }
-  //
-  // create ITS tracks from ESD tracks if not done before
-  //
-  for (Int_t itrack=0;itrack<ntracks;itrack++){
-    if (itsmap[itrack]>=0) continue;
-    AliITStrackMI * tpctrack = new AliITStrackMI(*(event->GetTrack(itrack)));
-    //tpctrack->fD[0] = tpctrack->GetD(GetX(),GetY());
-    //tpctrack->fD[1] = tpctrack->GetZat(GetX())-GetZ(); 
-    tpctrack->GetDZ(GetX(),GetY(),GetZ(),tpctrack->GetDP());   //I.B.
-    if (tpctrack->GetD(0)<20 && tpctrack->GetD(1)<20){
-      // tracks which can reach inner part of ITS
-      // propagate track to outer its volume - with correction for material
-      CorrectForTPCtoITSDeadZoneMaterial(tpctrack);  
-    }
-    itsmap[itrack] = nitstracks;
-    fOriginal.AddAt(tpctrack,nitstracks);
-    nitstracks++;
-  }
-  //
-  // fill temporary arrays
-  //
-  for (Int_t itrack=0;itrack<ntracks;itrack++){
-    AliESDtrack *  esdtrack = event->GetTrack(itrack);
-    Int_t          itsindex = itsmap[itrack];
-    AliITStrackMI *original = (AliITStrackMI*)fOriginal.At(itsmap[itrack]);
-    if (!original) continue;
-    AliITStrackMI *bestConst  = 0;
-    AliITStrackMI *bestLong   = 0;
-    AliITStrackMI *best       = 0;    
-    //
-    //
-    TObjArray * array    = (TObjArray*)  fTrackHypothesys.At(itsindex);
-    Int_t       hentries = (array==0) ?  0 : array->GetEntriesFast();
-    // Get best track with vertex constrain
-    for (Int_t ih=0;ih<hentries;ih++){
-      AliITStrackMI * trackh = (AliITStrackMI*)array->At(ih);
-      if (!trackh->GetConstrain()) continue;
-      if (!bestConst) bestConst = trackh;
-      if (trackh->GetNumberOfClusters()>5.0){
-       bestConst  = trackh;                         // full track -  with minimal chi2
-       break;
-      }
-      if (trackh->GetNumberOfClusters()+trackh->GetNDeadZone()<=bestConst->GetNumberOfClusters()+bestConst->GetNDeadZone())  continue;      
-      bestConst = trackh;
-      break;
-    }
-    // Get best long track without vertex constrain and best track without vertex constrain
-    for (Int_t ih=0;ih<hentries;ih++){
-      AliITStrackMI * trackh = (AliITStrackMI*)array->At(ih);
-      if (trackh->GetConstrain()) continue;
-      if (!best)     best     = trackh;
-      if (!bestLong) bestLong = trackh;
-      if (trackh->GetNumberOfClusters()>5.0){
-       bestLong  = trackh;                         // full track -  with minimal chi2
-       break;
-      }
-      if (trackh->GetNumberOfClusters()+trackh->GetNDeadZone()<=bestLong->GetNumberOfClusters()+bestLong->GetNDeadZone())  continue;      
-      bestLong = trackh;       
-    }
-    if (!best) {
-      best     = original;
-      bestLong = original;
-    }
-    //I.B. trackat0 = *bestLong;
-    new (&trackat0) AliITStrackMI(*bestLong);
-    Double_t xx,yy,zz,alpha; 
-    bestLong->GetGlobalXYZat(bestLong->GetX(),xx,yy,zz);
-    alpha = TMath::ATan2(yy,xx);    
-    trackat0.Propagate(alpha,0);      
-    // calculate normalized distances to the vertex 
-    //
-    Float_t ptfac  = (1.+100.*TMath::Abs(trackat0.GetC()));
-    if ( bestLong->GetNumberOfClusters()>3 ){      
-      dist[itsindex]      = trackat0.GetY();
-      norm[itsindex]      = ptfac*TMath::Sqrt(trackat0.GetSigmaY2());
-      normdist0[itsindex] = TMath::Abs(trackat0.GetY()/norm[itsindex]);
-      normdist1[itsindex] = TMath::Abs((trackat0.GetZ()-primvertex[2])/(ptfac*TMath::Sqrt(trackat0.GetSigmaZ2())));
-      normdist[itsindex]  = TMath::Sqrt(normdist0[itsindex]*normdist0[itsindex]+normdist1[itsindex]*normdist1[itsindex]);
-      if (!bestConst){
-       if (bestLong->GetNumberOfClusters()+bestLong->GetNDeadZone()<6) normdist[itsindex]*=2.;
-       if (bestLong->GetNumberOfClusters()+bestLong->GetNDeadZone()<5) normdist[itsindex]*=2.;
-       if (bestLong->GetNumberOfClusters()+bestLong->GetNDeadZone()<4) normdist[itsindex]*=2.;
-      }else{
-       if (bestConst->GetNumberOfClusters()+bestConst->GetNDeadZone()<6) normdist[itsindex]*=1.5;
-       if (bestConst->GetNumberOfClusters()+bestConst->GetNDeadZone()<5) normdist[itsindex]*=1.5;
-      }
-    }
-    else{      
-      if (bestConst&&bestConst->GetNumberOfClusters()+bestConst->GetNDeadZone()>4.5){
-       dist[itsindex] = bestConst->GetD(0);
-       norm[itsindex] = bestConst->GetDnorm(0);
-       normdist0[itsindex] = TMath::Abs(bestConst->GetD(0)/norm[itsindex]);
-       normdist1[itsindex] = TMath::Abs(bestConst->GetD(0)/norm[itsindex]);
-       normdist[itsindex]  = TMath::Sqrt(normdist0[itsindex]*normdist0[itsindex]+normdist1[itsindex]*normdist1[itsindex]);
-      }else{
-       dist[itsindex]      = trackat0.GetY();
-       norm[itsindex]      = ptfac*TMath::Sqrt(trackat0.GetSigmaY2());
-       normdist0[itsindex] = TMath::Abs(trackat0.GetY()/norm[itsindex]);
-       normdist1[itsindex] = TMath::Abs((trackat0.GetZ()-primvertex[2])/(ptfac*TMath::Sqrt(trackat0.GetSigmaZ2())));
-       normdist[itsindex]  = TMath::Sqrt(normdist0[itsindex]*normdist0[itsindex]+normdist1[itsindex]*normdist1[itsindex]);
-       if (TMath::Abs(trackat0.GetTgl())>1.05){
-         if (normdist[itsindex]<3) forbidden[itsindex]=kTRUE;
-         if (normdist[itsindex]>3) {
-           minr[itsindex] = TMath::Max(Float_t(40.),minr[itsindex]);
-         }
-       }
-      }
-    }
-    //
-    //-----------------------------------------------------------
-    //Forbid primary track candidates - 
-    //
-    //treetr->SetAlias("forbidden0","Tr0.fN<4&&Tr1.fN+Tr1.fNDeadZone>4.5");
-    //treetr->SetAlias("forbidden1","ND<3&&Tr1.fN+Tr1.fNDeadZone>5.5");
-    //treetr->SetAlias("forbidden2","ND<2&&Tr1.fClIndex[0]>0&&Tr1.fClIndex[0]>0");
-    //treetr->SetAlias("forbidden3","ND<1&&Tr1.fClIndex[0]>0");
-    //treetr->SetAlias("forbidden4","ND<4&&Tr1.fNormChi2[0]<2");
-    //treetr->SetAlias("forbidden5","ND<5&&Tr1.fNormChi2[0]<1");
-    //-----------------------------------------------------------
-    if (bestConst){
-      if (bestLong->GetNumberOfClusters()<4       && bestConst->GetNumberOfClusters()+bestConst->GetNDeadZone()>4.5)               forbidden[itsindex]=kTRUE;
-      if (normdist[itsindex]<3 && bestConst->GetNumberOfClusters()+bestConst->GetNDeadZone()>5.5)               forbidden[itsindex]=kTRUE;
-      if (normdist[itsindex]<2 && bestConst->GetClIndex(0)>0 && bestConst->GetClIndex(1)>0 ) forbidden[itsindex]=kTRUE;
-      if (normdist[itsindex]<1 && bestConst->GetClIndex(0)>0)                              forbidden[itsindex]=kTRUE;
-      if (normdist[itsindex]<4 && bestConst->GetNormChi2(0)<2)                             forbidden[itsindex]=kTRUE;
-      if (normdist[itsindex]<5 && bestConst->GetNormChi2(0)<1)                             forbidden[itsindex]=kTRUE;      
-      if (bestConst->GetNormChi2(0)<2.5) {
-       minPointAngle[itsindex]= 0.9999;
-       maxr[itsindex]         = 10;
-      }
-    }
-    //
-    //forbid daughter kink candidates
-    //
-    if (esdtrack->GetKinkIndex(0)>0) forbidden[itsindex] = kTRUE;
-    Bool_t isElectron = kTRUE;
-    Bool_t isProton   = kTRUE;
-    Double_t pid[5];
-    esdtrack->GetESDpid(pid);
-    for (Int_t i=1;i<5;i++){
-      if (pid[0]<pid[i]) isElectron= kFALSE;
-      if (pid[4]<pid[i]) isProton= kFALSE;
-    }
-    if (isElectron){
-      forbidden[itsindex]=kFALSE;      
-      normdist[itsindex]*=-1;
-    }
-    if (isProton){
-      if (normdist[itsindex]>2) forbidden[itsindex]=kFALSE;    
-      normdist[itsindex]*=-1;
-    }
-
-    //
-    // Causality cuts in TPC volume
-    //
-    if (esdtrack->GetTPCdensity(0,10) >0.6)  maxr[itsindex] = TMath::Min(Float_t(110),maxr[itsindex]);
-    if (esdtrack->GetTPCdensity(10,30)>0.6)  maxr[itsindex] = TMath::Min(Float_t(120),maxr[itsindex]);
-    if (esdtrack->GetTPCdensity(20,40)>0.6)  maxr[itsindex] = TMath::Min(Float_t(130),maxr[itsindex]);
-    if (esdtrack->GetTPCdensity(30,50)>0.6)  maxr[itsindex] = TMath::Min(Float_t(140),maxr[itsindex]);
-    //
-    if (esdtrack->GetTPCdensity(0,60)<0.4&&bestLong->GetNumberOfClusters()<3) minr[itsindex]=100;    
-    //
-    //
-    if (kFALSE){
-      cstream<<"Track"<<
-       "Tr0.="<<best<<
-       "Tr1.="<<((bestConst)? bestConst:dummy)<<
-       "Tr2.="<<bestLong<<
-       "Tr3.="<<&trackat0<<
-       "Esd.="<<esdtrack<<
-       "Dist="<<dist[itsindex]<<
-       "ND0="<<normdist0[itsindex]<<
-       "ND1="<<normdist1[itsindex]<<
-       "ND="<<normdist[itsindex]<<
-       "Pz="<<primvertex[2]<<
-       "Forbid="<<forbidden[itsindex]<<
-       "\n";
-      //
-    }
-    trackarray.AddAt(best,itsindex);
-    trackarrayc.AddAt(bestConst,itsindex);
-    trackarrayl.AddAt(bestLong,itsindex);
-    new (&helixes[itsindex]) AliHelix(*best);
-  }
-  //
-  //
-  //
-  // first iterration of V0 finder
-  //
-  for (Int_t iesd0=0;iesd0<ntracks;iesd0++){
-    Int_t itrack0 = itsmap[iesd0];
-    if (forbidden[itrack0]) continue;
-    AliITStrackMI * btrack0 = (AliITStrackMI*)trackarray.At(itrack0);
-    if (!btrack0) continue;    
-    if (btrack0->GetSign()>0) continue;
-    AliITStrackMI *trackc0 = (AliITStrackMI*)trackarrayc.At(itrack0);
-    //
-    for (Int_t iesd1=0;iesd1<ntracks;iesd1++){
-      Int_t itrack1 = itsmap[iesd1];
-      if (forbidden[itrack1]) continue;
-
-      AliITStrackMI * btrack1 = (AliITStrackMI*)trackarray.At(itrack1); 
-      if (!btrack1) continue;
-      if (btrack1->GetSign()<0) continue;
-      Bool_t isGold = kFALSE;
-      if (TMath::Abs(TMath::Abs(btrack0->GetLabel())-TMath::Abs(btrack1->GetLabel()))==1){
-       isGold = kTRUE;
-      }
-      AliITStrackMI *trackc1 = (AliITStrackMI*)trackarrayc.At(itrack1);
-      AliHelix &h1 = helixes[itrack0];
-      AliHelix &h2 = helixes[itrack1];
-      //
-      // find linear distance
-      Double_t rmin =0;
-      //
-      //
-      //
-      Double_t phase[2][2],radius[2];
-      Int_t  points = h1.GetRPHIintersections(h2, phase, radius);
-      if    (points==0)  continue;
-      Double_t delta[2]={1000000,1000000};        
-      rmin = radius[0];
-      h1.ParabolicDCA(h2,phase[0][0],phase[0][1],radius[0],delta[0]);
-      if (points==2){    
-       if (radius[1]<rmin) rmin = radius[1];
-       h1.ParabolicDCA(h2,phase[1][0],phase[1][1],radius[1],delta[1]);
-      }
-      rmin = TMath::Sqrt(rmin);
-      Double_t distance = 0;
-      Double_t radiusC  = 0;
-      Int_t    iphase   = 0;
-      if (points==1 || delta[0]<delta[1]){
-       distance = TMath::Sqrt(delta[0]);
-       radiusC  = TMath::Sqrt(radius[0]);
-      }else{
-       distance = TMath::Sqrt(delta[1]);
-       radiusC  = TMath::Sqrt(radius[1]);
-       iphase=1;
-      }
-      if (radiusC<TMath::Max(minr[itrack0],minr[itrack1]))    continue;
-      if (radiusC>TMath::Min(maxr[itrack0],maxr[itrack1]))     continue; 
-      Float_t maxDist  = TMath::Min(kMaxDist,Float_t(kMaxDist0+radiusC*kMaxDist1));      
-      if (distance>maxDist) continue;
-      Float_t pointAngle = h1.GetPointAngle(h2,phase[iphase],primvertex);
-      if (pointAngle<TMath::Max(minPointAngle[itrack0],minPointAngle[itrack1])) continue;
-      //
-      //
-      //      Double_t distance = TestV0(h1,h2,pvertex,rmin);
-      //
-      //       if (distance>maxDist)           continue;
-      //       if (pvertex->GetRr()<kMinR)     continue;
-      //       if (pvertex->GetRr()>kMaxR)     continue;
-      AliITStrackMI * track0=btrack0;
-      AliITStrackMI * track1=btrack1;
-      //      if (pvertex->GetRr()<3.5){  
-      if (radiusC<3.5){  
-       //use longest tracks inside the pipe
-       track0 = (AliITStrackMI*)trackarrayl.At(itrack0);
-       track1 = (AliITStrackMI*)trackarrayl.At(itrack1);
-      }      
-      //
-      //
-      pvertex->SetParamN(*track0);
-      pvertex->SetParamP(*track1);
-      pvertex->Update(primvertex);
-      pvertex->SetClusters(track0->ClIndex(),track1->ClIndex());  // register clusters
-
-      if (pvertex->GetRr()<kMinR) continue;
-      if (pvertex->GetRr()>kMaxR) continue;
-      if (pvertex->GetV0CosineOfPointingAngle()<kMinPointAngle) continue;
-//Bo:      if (pvertex->GetDist2()>maxDist) continue;
-      if (pvertex->GetDcaV0Daughters()>maxDist) continue;
-//Bo:        pvertex->SetLab(0,track0->GetLabel());
-//Bo:        pvertex->SetLab(1,track1->GetLabel());
-      pvertex->SetIndex(0,track0->GetESDtrack()->GetID());
-      pvertex->SetIndex(1,track1->GetESDtrack()->GetID());
-      //      
-      AliITStrackMI * htrackc0 = trackc0 ? trackc0:dummy;      
-      AliITStrackMI * htrackc1 = trackc1 ? trackc1:dummy;
-
-      //
-      //
-      TObjArray * array0b     = (TObjArray*)fBestHypothesys.At(itrack0);
-      if (!array0b&&pvertex->GetRr()<40 && TMath::Abs(track0->GetTgl())<1.1) 
-       FollowProlongationTree((AliITStrackMI*)fOriginal.At(itrack0),itrack0, kFALSE);
-      TObjArray * array1b    = (TObjArray*)fBestHypothesys.At(itrack1);
-      if (!array1b&&pvertex->GetRr()<40 && TMath::Abs(track1->GetTgl())<1.1) 
-       FollowProlongationTree((AliITStrackMI*)fOriginal.At(itrack1),itrack1, kFALSE);
-      //
-      AliITStrackMI * track0b = (AliITStrackMI*)fOriginal.At(itrack0);       
-      AliITStrackMI * track1b = (AliITStrackMI*)fOriginal.At(itrack1);
-      AliITStrackMI * track0l = (AliITStrackMI*)fOriginal.At(itrack0);       
-      AliITStrackMI * track1l = (AliITStrackMI*)fOriginal.At(itrack1);
-      
-      Float_t minchi2before0=16;
-      Float_t minchi2before1=16;
-      Float_t minchi2after0 =16;
-      Float_t minchi2after1 =16;
-      Double_t xrp[3]; pvertex->GetXYZ(xrp[0],xrp[1],xrp[2]);  //I.B.
-      Int_t maxLayer = GetNearestLayer(xrp);                   //I.B.
-      
-      if (array0b) for (Int_t i=0;i<5;i++){
-       // best track after vertex
-       AliITStrackMI * btrack = (AliITStrackMI*)array0b->At(i);
-       if (!btrack) continue;
-       if (btrack->GetNumberOfClusters()>track0l->GetNumberOfClusters()) track0l = btrack;     
-       //      if (btrack->fX<pvertex->GetRr()-2.-0.5/(0.1+pvertex->GetAnglep()[2])) {
-       if (btrack->GetX()<pvertex->GetRr()-2.) {
-         if ( (maxLayer>i+2|| (i==0)) && btrack->GetNumberOfClusters()==(6-i)&&i<3){
-           Float_t sumchi2= 0;
-           Float_t sumn   = 0;
-           if (maxLayer<3){   // take prim vertex as additional measurement
-             if (normdist[itrack0]>0 && htrackc0){
-               sumchi2 += TMath::Min((3.-maxLayer)*normdist[itrack0]*normdist[itrack0],16.);
-             }else{
-               sumchi2 +=  TMath::Min((3.-maxLayer)*(3*normdist[itrack0]*normdist[itrack0]+3.),16.);
-             }
-             sumn    +=  3-maxLayer;
-           }
-           for (Int_t ilayer=i;ilayer<maxLayer;ilayer++){
-             sumn+=1.;       
-             if (!btrack->GetClIndex(ilayer)){
-               sumchi2+=25;
-               continue;
-             }else{
-               Int_t c=( btrack->GetClIndex(ilayer) & 0x0fffffff);
-               for (Int_t itrack=0;itrack<4;itrack++){
-                 if (fgLayers[ilayer].GetClusterTracks(itrack,c)>=0 && fgLayers[ilayer].GetClusterTracks(itrack,c)!=itrack0){
-                   sumchi2+=18.;  //shared cluster
-                   break;
-                 }
-               }
-               sumchi2+=btrack->GetDy(ilayer)*btrack->GetDy(ilayer)/(btrack->GetSigmaY(ilayer)*btrack->GetSigmaY(ilayer));
-               sumchi2+=btrack->GetDz(ilayer)*btrack->GetDz(ilayer)/(btrack->GetSigmaZ(ilayer)*btrack->GetSigmaZ(ilayer));            
-             }
-           }
-           sumchi2/=sumn;
-           if (sumchi2<minchi2before0) minchi2before0=sumchi2; 
-         }
-         continue;   //safety space - Geo manager will give exact layer
-       }
-       track0b       = btrack;
-       minchi2after0 = btrack->GetNormChi2(i);
-       break;
-      }
-      if (array1b) for (Int_t i=0;i<5;i++){
-       // best track after vertex
-       AliITStrackMI * btrack = (AliITStrackMI*)array1b->At(i);
-       if (!btrack) continue;
-       if (btrack->GetNumberOfClusters()>track1l->GetNumberOfClusters()) track1l = btrack;     
-       //      if (btrack->fX<pvertex->GetRr()-2-0.5/(0.1+pvertex->GetAnglep()[2])){
-       if (btrack->GetX()<pvertex->GetRr()-2){
-         if ((maxLayer>i+2 || (i==0))&&btrack->GetNumberOfClusters()==(6-i)&&(i<3)){
-           Float_t sumchi2= 0;
-           Float_t sumn   = 0;
-           if (maxLayer<3){   // take prim vertex as additional measurement
-             if (normdist[itrack1]>0 && htrackc1){
-               sumchi2 +=  TMath::Min((3.-maxLayer)*normdist[itrack1]*normdist[itrack1],16.);
-             }else{
-               sumchi2 += TMath::Min((3.-maxLayer)*(3*normdist[itrack1]*normdist[itrack1]+3.),16.);
-             }
-             sumn    +=  3-maxLayer;
-           }
-           for (Int_t ilayer=i;ilayer<maxLayer;ilayer++){
-             sumn+=1.;
-             if (!btrack->GetClIndex(ilayer)){
-               sumchi2+=30;
-               continue;
-             }else{
-               Int_t c=( btrack->GetClIndex(ilayer) & 0x0fffffff);
-               for (Int_t itrack=0;itrack<4;itrack++){
-                 if (fgLayers[ilayer].GetClusterTracks(itrack,c)>=0 && fgLayers[ilayer].GetClusterTracks(itrack,c)!=itrack1){
-                   sumchi2+=18.;  //shared cluster
-                   break;
-                 }
-               }
-               sumchi2+=btrack->GetDy(ilayer)*btrack->GetDy(ilayer)/(btrack->GetSigmaY(ilayer)*btrack->GetSigmaY(ilayer));
-               sumchi2+=btrack->GetDz(ilayer)*btrack->GetDz(ilayer)/(btrack->GetSigmaZ(ilayer)*btrack->GetSigmaZ(ilayer));            
-             }
-           }
-           sumchi2/=sumn;
-           if (sumchi2<minchi2before1) minchi2before1=sumchi2; 
-         }
-         continue;   //safety space - Geo manager will give exact layer           
-       }
-       track1b = btrack;
-       minchi2after1 = btrack->GetNormChi2(i);
-       break;
-      }
-      //
-      // position resolution - used for DCA cut
-      Float_t sigmad = track0b->GetSigmaY2()+track0b->GetSigmaZ2()+track1b->GetSigmaY2()+track1b->GetSigmaZ2()+
-       (track0b->GetX()-pvertex->GetRr())*(track0b->GetX()-pvertex->GetRr())*(track0b->GetSigmaSnp2()+track0b->GetSigmaTgl2())+
-       (track1b->GetX()-pvertex->GetRr())*(track1b->GetX()-pvertex->GetRr())*(track1b->GetSigmaSnp2()+track1b->GetSigmaTgl2());
-      sigmad =TMath::Sqrt(sigmad)+0.04;
-      if (pvertex->GetRr()>50){
-       Double_t cov0[15],cov1[15];
-       track0b->GetESDtrack()->GetInnerExternalCovariance(cov0);
-       track1b->GetESDtrack()->GetInnerExternalCovariance(cov1);
-       sigmad = cov0[0]+cov0[2]+cov1[0]+cov1[2]+
-         (80.-pvertex->GetRr())*(80.-pvertex->GetRr())*(cov0[5]+cov0[9])+
-         (80.-pvertex->GetRr())*(80.-pvertex->GetRr())*(cov1[5]+cov1[9]);
-       sigmad =TMath::Sqrt(sigmad)+0.05;
-      }
-      //       
-      AliV0 vertex2;
-      vertex2.SetParamN(*track0b);
-      vertex2.SetParamP(*track1b);
-      vertex2.Update(primvertex);
-      //Bo:      if (vertex2.GetDist2()<=pvertex->GetDist2()&&(vertex2.GetV0CosineOfPointingAngle()>=pvertex->GetV0CosineOfPointingAngle())){
-      if (vertex2.GetDcaV0Daughters()<=pvertex->GetDcaV0Daughters()&&(vertex2.GetV0CosineOfPointingAngle()>=pvertex->GetV0CosineOfPointingAngle())){
-       pvertex->SetParamN(*track0b);
-       pvertex->SetParamP(*track1b);
-       pvertex->Update(primvertex);
-       pvertex->SetClusters(track0b->ClIndex(),track1b->ClIndex());  // register clusters
-       pvertex->SetIndex(0,track0->GetESDtrack()->GetID());
-       pvertex->SetIndex(1,track1->GetESDtrack()->GetID());
-      }
-      pvertex->SetDistSigma(sigmad);
-      //Bo:      pvertex->SetDistNorm(pvertex->GetDist2()/sigmad);       
-      pvertex->SetNormDCAPrim(normdist[itrack0],normdist[itrack1]);
-      //
-      // define likelihhod and causalities
-      //
-      Float_t pa0=1, pa1=1, pb0=0.26, pb1=0.26;      
-      if (maxLayer<1){
-       Float_t fnorm0 = normdist[itrack0];
-       if (fnorm0<0) fnorm0*=-3;
-       Float_t fnorm1 = normdist[itrack1];
-       if (fnorm1<0) fnorm1*=-3;
-       if (pvertex->GetAnglep()[2]>0.1 ||  (pvertex->GetRr()<10.5)&& pvertex->GetAnglep()[2]>0.05 || pvertex->GetRr()<3){
-         pb0    =  TMath::Exp(-TMath::Min(fnorm0,Float_t(16.))/12.);
-         pb1    =  TMath::Exp(-TMath::Min(fnorm1,Float_t(16.))/12.);
-       }
-       pvertex->SetChi2Before(normdist[itrack0]);
-       pvertex->SetChi2After(normdist[itrack1]);       
-       pvertex->SetNAfter(0);
-       pvertex->SetNBefore(0);
-      }else{
-       pvertex->SetChi2Before(minchi2before0);
-       pvertex->SetChi2After(minchi2before1);
-        if (pvertex->GetAnglep()[2]>0.1 || ( pvertex->GetRr()<10.5 && pvertex->GetAnglep()[2]>0.05) || pvertex->GetRr()<3){
-          pb0    =  TMath::Exp(-TMath::Min(minchi2before0,Float_t(16))/12.);
-          pb1    =  TMath::Exp(-TMath::Min(minchi2before1,Float_t(16))/12.);
-        }
-        pvertex->SetNAfter(maxLayer);
-        pvertex->SetNBefore(maxLayer);      
-      }
-      if (pvertex->GetRr()<90){
-       pa0  *= TMath::Min(track0->GetESDtrack()->GetTPCdensity(0,60),Double_t(1.));
-       pa1  *= TMath::Min(track1->GetESDtrack()->GetTPCdensity(0,60),Double_t(1.));
-      }
-      if (pvertex->GetRr()<20){
-       pa0  *= (0.2+TMath::Exp(-TMath::Min(minchi2after0,Float_t(16))/8.))/1.2;
-       pa1  *= (0.2+TMath::Exp(-TMath::Min(minchi2after1,Float_t(16))/8.))/1.2;
-      }
-      //
-      pvertex->SetCausality(pb0,pb1,pa0,pa1);
-      //
-      //  Likelihood calculations  - apply cuts
-      //         
-      Bool_t v0OK = kTRUE;
-      Float_t p12 = pvertex->GetParamP()->GetParameter()[4]*pvertex->GetParamP()->GetParameter()[4];
-      p12        += pvertex->GetParamN()->GetParameter()[4]*pvertex->GetParamN()->GetParameter()[4];
-      p12         = TMath::Sqrt(p12);                             // "mean" momenta
-      Float_t    sigmap0   = 0.0001+0.001/(0.1+pvertex->GetRr()); 
-      Float_t    sigmap    = 0.5*sigmap0*(0.6+0.4*p12);           // "resolution: of point angle - as a function of radius and momenta
-
-      Float_t causalityA  = (1.0-pvertex->GetCausalityP()[0])*(1.0-pvertex->GetCausalityP()[1]);
-      Float_t causalityB  = TMath::Sqrt(TMath::Min(pvertex->GetCausalityP()[2],Double_t(0.7))*
-                                       TMath::Min(pvertex->GetCausalityP()[3],Double_t(0.7)));
-      //
-      //Bo:      Float_t likelihood0 = (TMath::Exp(-pvertex->GetDistNorm())+0.1) *(pvertex->GetDist2()<0.5)*(pvertex->GetDistNorm()<5);
-      Float_t lDistNorm = pvertex->GetDcaV0Daughters()/pvertex->GetDistSigma();
-      Float_t likelihood0 = (TMath::Exp(-lDistNorm)+0.1) *(pvertex->GetDcaV0Daughters()<0.5)*(lDistNorm<5);
-
-      Float_t likelihood1 = TMath::Exp(-(1.0001-pvertex->GetV0CosineOfPointingAngle())/sigmap)+
-       0.4*TMath::Exp(-(1.0001-pvertex->GetV0CosineOfPointingAngle())/(4.*sigmap))+
-       0.4*TMath::Exp(-(1.0001-pvertex->GetV0CosineOfPointingAngle())/(8.*sigmap))+
-       0.1*TMath::Exp(-(1.0001-pvertex->GetV0CosineOfPointingAngle())/0.01);
-      //
-      if (causalityA<kCausality0Cut)                                          v0OK = kFALSE;
-      if (TMath::Sqrt(likelihood0*likelihood1)<kLikelihood01Cut)              v0OK = kFALSE;
-      if (likelihood1<kLikelihood1Cut)                                        v0OK = kFALSE;
-      if (TMath::Power(likelihood0*likelihood1*causalityB,0.33)<kCombinedCut) v0OK = kFALSE;
-      
-      //
-      //
-      if (kFALSE){     
-       Bool_t gold = TMath::Abs(TMath::Abs(track0->GetLabel())-TMath::Abs(track1->GetLabel()))==1;
-       cstream<<"It0"<<
-         "Tr0.="<<track0<<                       //best without constrain
-         "Tr1.="<<track1<<                       //best without constrain  
-         "Tr0B.="<<track0b<<                     //best without constrain  after vertex
-         "Tr1B.="<<track1b<<                     //best without constrain  after vertex 
-         "Tr0C.="<<htrackc0<<                    //best with constrain     if exist
-         "Tr1C.="<<htrackc1<<                    //best with constrain     if exist
-         "Tr0L.="<<track0l<<                     //longest best           
-         "Tr1L.="<<track1l<<                     //longest best
-         "Esd0.="<<track0->GetESDtrack()<<           // esd track0 params
-         "Esd1.="<<track1->GetESDtrack()<<           // esd track1 params
-         "V0.="<<pvertex<<                       //vertex properties
-         "V0b.="<<&vertex2<<                       //vertex properties at "best" track
-         "ND0="<<normdist[itrack0]<<             //normalize distance for track0
-         "ND1="<<normdist[itrack1]<<             //normalize distance for track1
-         "Gold="<<gold<<                         //
-         //      "RejectBase="<<rejectBase<<             //rejection in First itteration
-         "OK="<<v0OK<<
-         "rmin="<<rmin<<
-         "sigmad="<<sigmad<<
-         "\n";
-      }      
-      //if (rejectBase) continue;
-      //
-      pvertex->SetStatus(0);
-      //      if (rejectBase) {
-      //       pvertex->SetStatus(-100);
-      //}
-      if (pvertex->GetV0CosineOfPointingAngle()>kMinPointAngle2) {
-       //Bo:     pvertex->SetESDindexes(track0->GetESDtrack()->GetID(),track1->GetESDtrack()->GetID());
-       pvertex->SetIndex(0,track0->GetESDtrack()->GetID());//Bo: consistency 0 for neg
-       pvertex->SetIndex(1,track1->GetESDtrack()->GetID());//Bo: consistency 1 for pos
-       if (v0OK){
-         //      AliV0vertex vertexjuri(*track0,*track1);
-         //      vertexjuri.SetESDindexes(track0->fESDtrack->GetID(),track1->fESDtrack->GetID());
-         //      event->AddV0(&vertexjuri);
-         pvertex->SetStatus(100);
-       }
-        pvertex->SetOnFlyStatus(kTRUE);
-        pvertex->ChangeMassHypothesis(kK0Short);
-       event->AddV0(pvertex);
-      }
-    }
-  }
-  //
-  //
-  // delete temporary arrays
-  //  
-  delete[] forbidden;
-  delete[] minPointAngle;
-  delete[] maxr;
-  delete[] minr;
-  delete[] norm;
-  delete[] normdist;
-  delete[] normdist1;
-  delete[] normdist0;
-  delete[] dist;
-  delete[] itsmap;
-  delete[] helixes;
-  delete   pvertex;
-}
-//------------------------------------------------------------------------
-void AliITStrackerMI::RefitV02(AliESDEvent *event)
-{
-  //
-  //try to refit  V0s in the third path of the reconstruction
-  //
-  TTreeSRedirector &cstream = *fDebugStreamer;
-  //
-  Int_t  nv0s = event->GetNumberOfV0s();
-  Float_t primvertex[3]={GetX(),GetY(),GetZ()};
-  AliV0 v0temp;
-  for (Int_t iv0 = 0; iv0<nv0s;iv0++){
-    AliV0 * v0mi = (AliV0*)event->GetV0(iv0);
-    if (!v0mi) continue;
-    Int_t     itrack0   = v0mi->GetIndex(0);
-    Int_t     itrack1   = v0mi->GetIndex(1);
-    AliESDtrack *esd0   = event->GetTrack(itrack0);
-    AliESDtrack *esd1   = event->GetTrack(itrack1);
-    if (!esd0||!esd1) continue;
-    AliITStrackMI tpc0(*esd0);  
-    AliITStrackMI tpc1(*esd1);
-    Double_t x,y,z; v0mi->GetXYZ(x,y,z); //I.B. 
-    Double_t alpha =TMath::ATan2(y,x);   //I.B.
-    if (v0mi->GetRr()>85){
-      if (tpc0.Propagate(alpha,v0mi->GetRr())&&tpc1.Propagate(alpha,v0mi->GetRr())){
-       v0temp.SetParamN(tpc0);
-       v0temp.SetParamP(tpc1);
-       v0temp.Update(primvertex);
-       if (kFALSE) cstream<<"Refit"<<
-         "V0.="<<v0mi<<
-         "V0refit.="<<&v0temp<<
-         "Tr0.="<<&tpc0<<
-         "Tr1.="<<&tpc1<<
-         "\n";
-       //Bo:   if (v0temp.GetDist2()<v0mi->GetDist2() || v0temp.GetV0CosineOfPointingAngle()>v0mi->GetV0CosineOfPointingAngle()){
-       if (v0temp.GetDcaV0Daughters()<v0mi->GetDcaV0Daughters() || v0temp.GetV0CosineOfPointingAngle()>v0mi->GetV0CosineOfPointingAngle()){
-         v0mi->SetParamN(tpc0);
-         v0mi->SetParamP(tpc1);
-         v0mi->Update(primvertex);
-       }
-      }
-      continue;
-    }
-    if (v0mi->GetRr()>35){
-      CorrectForTPCtoITSDeadZoneMaterial(&tpc0);
-      CorrectForTPCtoITSDeadZoneMaterial(&tpc1);
-      if (tpc0.Propagate(alpha,v0mi->GetRr())&&tpc1.Propagate(alpha,v0mi->GetRr())){
-       v0temp.SetParamN(tpc0);
-       v0temp.SetParamP(tpc1);
-       v0temp.Update(primvertex);
-       if (kFALSE) cstream<<"Refit"<<
-         "V0.="<<v0mi<<
-         "V0refit.="<<&v0temp<<
-         "Tr0.="<<&tpc0<<
-         "Tr1.="<<&tpc1<<
-         "\n";
-       //Bo:   if (v0temp.GetDist2()<v0mi->GetDist2() || v0temp.GetV0CosineOfPointingAngle()>v0mi->GetV0CosineOfPointingAngle()){
-       if (v0temp.GetDcaV0Daughters()<v0mi->GetDcaV0Daughters() || v0temp.GetV0CosineOfPointingAngle()>v0mi->GetV0CosineOfPointingAngle()){
-         v0mi->SetParamN(tpc0);
-         v0mi->SetParamP(tpc1);
-         v0mi->Update(primvertex);
-       }       
-      }
-      continue;
-    }
-    CorrectForTPCtoITSDeadZoneMaterial(&tpc0);
-    CorrectForTPCtoITSDeadZoneMaterial(&tpc1);    
-    //    if (tpc0.Propagate(alpha,v0mi->GetRr())&&tpc1.Propagate(alpha,v0mi->GetRr())){
-    if (RefitAt(v0mi->GetRr(),&tpc0, v0mi->GetClusters(0)) && RefitAt(v0mi->GetRr(),&tpc1, v0mi->GetClusters(1))){
-      v0temp.SetParamN(tpc0);
-      v0temp.SetParamP(tpc1);
-      v0temp.Update(primvertex);
-      if (kFALSE) cstream<<"Refit"<<
-       "V0.="<<v0mi<<
-       "V0refit.="<<&v0temp<<
-       "Tr0.="<<&tpc0<<
-       "Tr1.="<<&tpc1<<
-       "\n";
-      //Bo:      if (v0temp.GetDist2()<v0mi->GetDist2() || v0temp.GetV0CosineOfPointingAngle()>v0mi->GetV0CosineOfPointingAngle()){
-      if (v0temp.GetDcaV0Daughters()<v0mi->GetDcaV0Daughters() || v0temp.GetV0CosineOfPointingAngle()>v0mi->GetV0CosineOfPointingAngle()){
-       v0mi->SetParamN(tpc0);
-       v0mi->SetParamP(tpc1);
-       v0mi->Update(primvertex);
-      }        
-    }    
-  }
-}
-//------------------------------------------------------------------------
 void AliITStrackerMI::BuildMaterialLUT(TString material) {
   //--------------------------------------------------------------------
   // Fill a look-up table with mean material
@@ -4320,8 +4042,8 @@ void AliITStrackerMI::BuildMaterialLUT(TString material) {
   Double_t point1[3],point2[3];
   Double_t phi,cosphi,sinphi,z;
   // 0-5 layers, 6 pipe, 7-8 shields 
-  Double_t rmin[9]={ 3.5, 5.5,13.0,22.0,35.0,41.0, 2.0, 7.5,25.0};
-  Double_t rmax[9]={ 5.5, 7.3,17.0,26.0,41.0,47.0, 3.0,10.5,30.0};
+  Double_t rmin[9]={ 3.5, 5.5,13.0,22.0,35.0,41.0, 2.0, 8.0,25.0};
+  Double_t rmax[9]={ 5.5, 8.0,17.0,26.0,41.0,47.0, 3.0,10.5,30.0};
 
   Int_t ifirst=0,ilast=0;  
   if(material.Contains("Pipe")) {
@@ -4384,13 +4106,14 @@ Int_t AliITStrackerMI::CorrectForPipeMaterial(AliITStrackMI *t,
   //-------------------------------------------------------------------
   // Propagate beyond beam pipe and correct for material
   // (material budget in different ways according to fUseTGeo value)
+  // Add time if going outward (PropagateTo or PropagateToTGeo)
   //-------------------------------------------------------------------
 
   // Define budget mode:
   // 0: material from AliITSRecoParam (hard coded)
-  // 1: material from TGeo (on the fly)
+  // 1: material from TGeo in one step (on the fly)
   // 2: material from lut
-  // 3: material from TGeo (same for all hypotheses)
+  // 3: material from TGeo in one step (same for all hypotheses)
   Int_t mode;
   switch(fUseTGeo) {
   case 0:
@@ -4420,46 +4143,46 @@ Int_t AliITStrackerMI::CorrectForPipeMaterial(AliITStrackMI *t,
 
   Float_t  dir = (direction.Contains("inward") ? 1. : -1.);
   Double_t rToGo=(dir>0 ? AliITSRecoParam::GetrInsidePipe() : AliITSRecoParam::GetrOutsidePipe());
-  Double_t xToGo; t->GetLocalXat(rToGo,xToGo);
+  Double_t xToGo;
+  if (!t->GetLocalXat(rToGo,xToGo)) return 0;
 
   Double_t xOverX0,x0,lengthTimesMeanDensity;
-  Bool_t anglecorr=kTRUE;
 
   switch(mode) {
   case 0:
     xOverX0 = AliITSRecoParam::GetdPipe();
     x0 = AliITSRecoParam::GetX0Be();
     lengthTimesMeanDensity = xOverX0*x0;
+    lengthTimesMeanDensity *= dir;
+    if (!t->PropagateTo(xToGo,xOverX0,lengthTimesMeanDensity/xOverX0)) return 0;
     break;
   case 1:
     if (!t->PropagateToTGeo(xToGo,1)) return 0;
-    return 1;
     break;
   case 2:
     if(fxOverX0Pipe<0) BuildMaterialLUT("Pipe");  
     xOverX0 = fxOverX0Pipe;
     lengthTimesMeanDensity = fxTimesRhoPipe;
+    lengthTimesMeanDensity *= dir;
+    if (!t->PropagateTo(xToGo,xOverX0,lengthTimesMeanDensity/xOverX0)) return 0;
     break;
   case 3:
     if(!fxOverX0PipeTrks || index<0 || index>=fNtracks) Error("CorrectForPipeMaterial","Incorrect usage of UseTGeo option!\n");
     if(fxOverX0PipeTrks[index]<0) {
       if (!t->PropagateToTGeo(xToGo,1,xOverX0,lengthTimesMeanDensity)) return 0;
       Double_t angle=TMath::Sqrt((1.+t->GetTgl()*t->GetTgl())/
-                                (1.-t->GetSnp()*t->GetSnp()));
+                                ((1.-t->GetSnp())*(1.+t->GetSnp())));
       fxOverX0PipeTrks[index] = TMath::Abs(xOverX0)/angle;
       fxTimesRhoPipeTrks[index] = TMath::Abs(lengthTimesMeanDensity)/angle;
       return 1;
     }
     xOverX0 = fxOverX0PipeTrks[index];
     lengthTimesMeanDensity = fxTimesRhoPipeTrks[index];
+    lengthTimesMeanDensity *= dir;
+    if (!t->PropagateTo(xToGo,xOverX0,lengthTimesMeanDensity/xOverX0)) return 0;
     break;
   }
 
-  lengthTimesMeanDensity *= dir;
-
-  if (!t->AliExternalTrackParam::PropagateTo(xToGo,GetBz())) return 0;
-  if (!t->CorrectForMeanMaterial(xOverX0,lengthTimesMeanDensity,anglecorr)) return 0;  
-
   return 1;
 }
 //------------------------------------------------------------------------
@@ -4469,13 +4192,15 @@ Int_t AliITStrackerMI::CorrectForShieldMaterial(AliITStrackMI *t,
   //-------------------------------------------------------------------
   // Propagate beyond SPD or SDD shield and correct for material
   // (material budget in different ways according to fUseTGeo value)
+  // Add time if going outward (PropagateTo or PropagateToTGeo)
   //-------------------------------------------------------------------
 
   // Define budget mode:
   // 0: material from AliITSRecoParam (hard coded)
-  // 1: material from TGeo (on the fly)
+  // 1: material from TGeo in steps of X cm (on the fly)
+  //    X = AliITSRecoParam::GetStepSizeTGeo()
   // 2: material from lut
-  // 3: material from TGeo (same for all hypotheses)
+  // 3: material from TGeo in one step (same for all hypotheses)
   Int_t mode;
   switch(fUseTGeo) {
   case 0:
@@ -4512,51 +4237,59 @@ Int_t AliITStrackerMI::CorrectForShieldMaterial(AliITStrackMI *t,
     shieldindex=0;
   } else {
     Error("CorrectForShieldMaterial"," Wrong shield name\n");
-    //    printf("%s\n",shield.Data());
     return 0;
   }
-  Double_t xToGo; t->GetLocalXat(rToGo,xToGo);
+
+  // do nothing if we are already beyond the shield
+  Double_t rTrack = TMath::Sqrt(t->GetX()*t->GetX()+t->GetY()*t->GetY());
+  if(dir<0 && rTrack > rToGo) return 1; // going outward
+  if(dir>0 && rTrack < rToGo) return 1; // going inward
+
+
+  Double_t xToGo;
+  if (!t->GetLocalXat(rToGo,xToGo)) return 0;
 
   Int_t index=2*fCurrentEsdTrack+shieldindex;
 
   Double_t xOverX0,x0,lengthTimesMeanDensity;
-  Bool_t anglecorr=kTRUE;
+  Int_t nsteps=1;
 
   switch(mode) {
   case 0:
     xOverX0 = AliITSRecoParam::Getdshield(shieldindex);
     x0 = AliITSRecoParam::GetX0shield(shieldindex);
     lengthTimesMeanDensity = xOverX0*x0;
+    lengthTimesMeanDensity *= dir;
+    if (!t->PropagateTo(xToGo,xOverX0,lengthTimesMeanDensity/xOverX0)) return 0;
     break;
   case 1:
-    if (!t->PropagateToTGeo(xToGo,1)) return 0;
-    return 1;
+    nsteps= (Int_t)(TMath::Abs(t->GetX()-xToGo)/AliITSReconstructor::GetRecoParam()->GetStepSizeTGeo())+1;
+    if (!t->PropagateToTGeo(xToGo,nsteps)) return 0; // cross the material and apply correction
     break;
   case 2:
     if(fxOverX0Shield[shieldindex]<0) BuildMaterialLUT("Shields");  
     xOverX0 = fxOverX0Shield[shieldindex];
     lengthTimesMeanDensity = fxTimesRhoShield[shieldindex];
+    lengthTimesMeanDensity *= dir;
+    if (!t->PropagateTo(xToGo,xOverX0,lengthTimesMeanDensity/xOverX0)) return 0;
     break;
   case 3:
     if(!fxOverX0ShieldTrks || index<0 || index>=2*fNtracks) Error("CorrectForShieldMaterial","Incorrect usage of UseTGeo option!\n");
     if(fxOverX0ShieldTrks[index]<0) {
       if (!t->PropagateToTGeo(xToGo,1,xOverX0,lengthTimesMeanDensity)) return 0;
       Double_t angle=TMath::Sqrt((1.+t->GetTgl()*t->GetTgl())/
-                                (1.-t->GetSnp()*t->GetSnp()));
+                                ((1.-t->GetSnp())*(1.+t->GetSnp())));
       fxOverX0ShieldTrks[index] = TMath::Abs(xOverX0)/angle;
       fxTimesRhoShieldTrks[index] = TMath::Abs(lengthTimesMeanDensity)/angle;
       return 1;
     }
     xOverX0 = fxOverX0ShieldTrks[index];
     lengthTimesMeanDensity = fxTimesRhoShieldTrks[index];
+    lengthTimesMeanDensity *= dir;
+    if (!t->PropagateTo(xToGo,xOverX0,lengthTimesMeanDensity/xOverX0)) return 0;
     break;
   }
 
-  lengthTimesMeanDensity *= dir;
-
-  if (!t->AliExternalTrackParam::PropagateTo(xToGo,GetBz())) return 0;
-  if (!t->CorrectForMeanMaterial(xOverX0,lengthTimesMeanDensity,anglecorr)) return 0;  
-
   return 1;
 }
 //------------------------------------------------------------------------
@@ -4567,13 +4300,15 @@ Int_t AliITStrackerMI::CorrectForLayerMaterial(AliITStrackMI *t,
   //-------------------------------------------------------------------
   // Propagate beyond layer and correct for material
   // (material budget in different ways according to fUseTGeo value)
+  // Add time if going outward (PropagateTo or PropagateToTGeo)
   //-------------------------------------------------------------------
 
   // Define budget mode:
   // 0: material from AliITSRecoParam (hard coded)
-  // 1: material from TGeo (on the fly)
+  // 1: material from TGeo in stepsof X cm (on the fly)
+  //    X = AliITSRecoParam::GetStepSizeTGeo()
   // 2: material from lut
-  // 3: material from TGeo (same for all hypotheses)
+  // 3: material from TGeo in one step (same for all hypotheses)
   Int_t mode;
   switch(fUseTGeo) {
   case 0:
@@ -4605,56 +4340,59 @@ Int_t AliITStrackerMI::CorrectForLayerMaterial(AliITStrackMI *t,
   Double_t deltar=(layerindex<2 ? 0.10*r : 0.05*r);
 
   Double_t rToGo=TMath::Sqrt(t->GetX()*t->GetX()+t->GetY()*t->GetY())-deltar*dir;
-  Double_t xToGo; t->GetLocalXat(rToGo,xToGo);
+  Double_t xToGo;
+  if (!t->GetLocalXat(rToGo,xToGo)) return 0;
 
   Int_t index=6*fCurrentEsdTrack+layerindex;
 
-  // Bring the track beyond the material
-  if (!t->AliExternalTrackParam::PropagateTo(xToGo,GetBz())) return 0;
-  Double_t globXYZ[3];
-  t->GetXYZ(globXYZ);
 
   Double_t xOverX0=0.0,x0=0.0,lengthTimesMeanDensity=0.0;
-  Double_t mparam[7];
-  Bool_t anglecorr=kTRUE;
+  Int_t nsteps=1;
+
+  // back before material (no correction)
+  Double_t rOld,xOld;
+  rOld=TMath::Sqrt(oldGlobXYZ[0]*oldGlobXYZ[0]+oldGlobXYZ[1]*oldGlobXYZ[1]);
+  if (!t->GetLocalXat(rOld,xOld)) return 0;
+  if (!t->Propagate(xOld)) return 0;
 
   switch(mode) {
   case 0:
     xOverX0 = fgLayers[layerindex].GetThickness(t->GetY(),t->GetZ(),x0);
     lengthTimesMeanDensity = xOverX0*x0;
+    lengthTimesMeanDensity *= dir;
+    // Bring the track beyond the material
+    if (!t->PropagateTo(xToGo,xOverX0,lengthTimesMeanDensity/xOverX0)) return 0;
     break;
   case 1:
-    AliTracker::MeanMaterialBudget(oldGlobXYZ,globXYZ,mparam);
-    if(mparam[1]>900000) return 0;
-    xOverX0=mparam[1];
-    lengthTimesMeanDensity=mparam[0]*mparam[4];
-    anglecorr=kFALSE;
+    nsteps = (Int_t)(TMath::Abs(xOld-xToGo)/AliITSReconstructor::GetRecoParam()->GetStepSizeTGeo())+1;
+    if (!t->PropagateToTGeo(xToGo,nsteps)) return 0; // cross the material and apply correction
     break;
   case 2:
     if(fxOverX0Layer[layerindex]<0) BuildMaterialLUT("Layers");  
     xOverX0 = fxOverX0Layer[layerindex];
     lengthTimesMeanDensity = fxTimesRhoLayer[layerindex];
+    lengthTimesMeanDensity *= dir;
+    // Bring the track beyond the material
+    if (!t->PropagateTo(xToGo,xOverX0,lengthTimesMeanDensity/xOverX0)) return 0;
     break;
   case 3:
     if(!fxOverX0LayerTrks || index<0 || index>=6*fNtracks) Error("CorrectForLayerMaterial","Incorrect usage of UseTGeo option!\n");
     if(fxOverX0LayerTrks[index]<0) {
-      AliTracker::MeanMaterialBudget(oldGlobXYZ,globXYZ,mparam);
-      if(mparam[1]>900000) return 0;
+      nsteps = (Int_t)(TMath::Abs(xOld-xToGo)/AliITSReconstructor::GetRecoParam()->GetStepSizeTGeo())+1;
+      if (!t->PropagateToTGeo(xToGo,nsteps,xOverX0,lengthTimesMeanDensity)) return 0;
       Double_t angle=TMath::Sqrt((1.+t->GetTgl()*t->GetTgl())/
-                                (1.-t->GetSnp()*t->GetSnp()));
-      xOverX0=mparam[1]/angle;
-      lengthTimesMeanDensity=mparam[0]*mparam[4]/angle;
-      fxOverX0LayerTrks[index] = TMath::Abs(xOverX0);
-      fxTimesRhoLayerTrks[index] = TMath::Abs(lengthTimesMeanDensity);
+                                ((1.-t->GetSnp())*(1.+t->GetSnp())));
+      fxOverX0LayerTrks[index] = TMath::Abs(xOverX0)/angle;
+      fxTimesRhoLayerTrks[index] = TMath::Abs(lengthTimesMeanDensity)/angle;
+      return 1;
     }
     xOverX0 = fxOverX0LayerTrks[index];
     lengthTimesMeanDensity = fxTimesRhoLayerTrks[index];
+    lengthTimesMeanDensity *= dir;
+    if (!t->PropagateTo(xToGo,xOverX0,lengthTimesMeanDensity/xOverX0)) return 0;
     break;
   }
 
-  lengthTimesMeanDensity *= dir;
-
-  if (!t->CorrectForMeanMaterial(xOverX0,lengthTimesMeanDensity,anglecorr)) return 0;  
 
   return 1;
 }
@@ -4714,26 +4452,540 @@ void AliITStrackerMI::DeleteTrksMaterialLUT() {
   return;
 }
 //------------------------------------------------------------------------
-Int_t AliITStrackerMI::SkipLayer(AliITStrackMI *track,
-                                Int_t ilayer,Int_t idet) const {
+void AliITStrackerMI::SetForceSkippingOfLayer() {
+  //-----------------------------------------------------------------
+  // Check if we are forced to skip layers
+  // either we set to skip them in RecoParam
+  // or they were off during data-taking
+  //-----------------------------------------------------------------
+
+  const AliEventInfo *eventInfo = GetEventInfo();
+  
+  for(Int_t l=0; l<AliITSgeomTGeo::kNLayers; l++) {
+    fForceSkippingOfLayer[l] = 0;
+    // check reco param
+    if(AliITSReconstructor::GetRecoParam()->GetLayersToSkip(l)) fForceSkippingOfLayer[l] = 1;
+    // check run info
+
+    if(eventInfo && 
+       AliITSReconstructor::GetRecoParam()->GetSkipSubdetsNotInTriggerCluster()) {
+      AliDebug(2,Form("GetEventInfo->GetTriggerCluster: %s",eventInfo->GetTriggerCluster()));
+      if(l==0 || l==1)  {
+       if(!strstr(eventInfo->GetTriggerCluster(),"ITSSPD")) fForceSkippingOfLayer[l] = 1;
+      } else if(l==2 || l==3) {
+       if(!strstr(eventInfo->GetTriggerCluster(),"ITSSDD")) fForceSkippingOfLayer[l] = 1; 
+      } else {
+       if(!strstr(eventInfo->GetTriggerCluster(),"ITSSSD")) fForceSkippingOfLayer[l] = 1;
+      } 
+    }
+  }
+  return;
+}
+//------------------------------------------------------------------------
+Int_t AliITStrackerMI::CheckSkipLayer(const AliITStrackMI *track,
+                                     Int_t ilayer,Int_t idet) const {
   //-----------------------------------------------------------------
   // This method is used to decide whether to allow a prolongation 
   // without clusters, because we want to skip the layer.
   // In this case the return value is > 0:
   // return 1: the user requested to skip a layer
-  // return 2: track outside z acceptance of SSD/SDD and will cross both SPD
+  // return 2: track outside z acceptance
   //-----------------------------------------------------------------
 
-  if (AliITSReconstructor::GetRecoParam()->GetLayersToSkip(ilayer)) return 1;
+  if (ForceSkippingOfLayer(ilayer)) return 1;
+
+  Int_t innerLayCanSkip=0; // was 2, changed on 05.11.2009
 
-  if (idet<0 && ilayer>1 && AliITSReconstructor::GetRecoParam()->GetExtendedEtaAcceptance()) {
+  if (idet<0 &&  // out in z
+      ilayer>innerLayCanSkip && 
+      AliITSReconstructor::GetRecoParam()->GetExtendedEtaAcceptance()) {
     // check if track will cross SPD outer layer
     Double_t phiAtSPD2,zAtSPD2;
-    if(track->GetPhiZat(fgLayers[1].GetR(),phiAtSPD2,zAtSPD2)) {
+    if (track->GetPhiZat(fgLayers[1].GetR(),phiAtSPD2,zAtSPD2)) {
       if (TMath::Abs(zAtSPD2)<2.*AliITSRecoParam::GetSPDdetzlength()) return 2;
     }
+    return 2; // always allow skipping, changed on 05.11.2009
   }
 
   return 0;
 }
 //------------------------------------------------------------------------
+Int_t AliITStrackerMI::CheckDeadZone(AliITStrackMI *track,
+                                    Int_t ilayer,Int_t idet,
+                                    Double_t dz,Double_t dy,
+                                    Bool_t noClusters) const {
+  //-----------------------------------------------------------------
+  // This method is used to decide whether to allow a prolongation 
+  // without clusters, because there is a dead zone in the road.
+  // In this case the return value is > 0:
+  // return 1: dead zone at z=0,+-7cm in SPD
+  //     This method assumes that fSPDdetzcentre is ordered from -z to +z
+  // return 2: all road is "bad" (dead or noisy) from the OCDB
+  // return 3: at least a chip is "bad" (dead or noisy) from the OCDB
+  // return 4: at least a single channel is "bad" (dead or noisy) from the OCDB
+  //-----------------------------------------------------------------
+
+  // check dead zones at z=0,+-7cm in the SPD
+  if (ilayer<2 && !AliITSReconstructor::GetRecoParam()->GetAddVirtualClustersInDeadZone()) {
+    Double_t zmindead[3]={fSPDdetzcentre[0] + 0.5*AliITSRecoParam::GetSPDdetzlength(),
+                         fSPDdetzcentre[1] + 0.5*AliITSRecoParam::GetSPDdetzlength(),
+                         fSPDdetzcentre[2] + 0.5*AliITSRecoParam::GetSPDdetzlength()};
+    Double_t zmaxdead[3]={fSPDdetzcentre[1] - 0.5*AliITSRecoParam::GetSPDdetzlength(),
+                         fSPDdetzcentre[2] - 0.5*AliITSRecoParam::GetSPDdetzlength(),
+                         fSPDdetzcentre[3] - 0.5*AliITSRecoParam::GetSPDdetzlength()};
+    for (Int_t i=0; i<3; i++)
+      if (track->GetZ()-dz<zmaxdead[i] && track->GetZ()+dz>zmindead[i]) {
+       AliDebug(2,Form("crack SPD %d track z %f   %f   %f  %f\n",ilayer,track->GetZ(),dz,zmaxdead[i],zmindead[i]));
+       if (GetSPDDeadZoneProbability(track->GetZ(),TMath::Sqrt(track->GetSigmaZ2()))>0.1) return 1; 
+      } 
+  }
+
+  // check bad zones from OCDB
+  if (!AliITSReconstructor::GetRecoParam()->GetUseBadZonesFromOCDB()) return 0;
+
+  if (idet<0) return 0;
+
+  AliITSdetector &det=fgLayers[ilayer].GetDetector(idet);  
+
+  Int_t detType=-1;
+  Float_t detSizeFactorX=0.0001,detSizeFactorZ=0.0001;
+  if (ilayer==0 || ilayer==1) {        // ----------  SPD
+    detType = 0;
+  } else if (ilayer==2 || ilayer==3) { // ----------  SDD
+    detType = 1;
+    detSizeFactorX *= 2.;
+  } else if (ilayer==4 || ilayer==5) { // ----------  SSD
+    detType = 2;
+  }
+  AliITSsegmentation *segm = (AliITSsegmentation*)fkDetTypeRec->GetSegmentationModel(detType);
+  if (detType==2) segm->SetLayer(ilayer+1);
+  Float_t detSizeX = detSizeFactorX*segm->Dx(); 
+  Float_t detSizeZ = detSizeFactorZ*segm->Dz(); 
+
+  // check if the road overlaps with bad chips
+  Float_t xloc,zloc;
+  if(!(LocalModuleCoord(ilayer,idet,track,xloc,zloc)))return 0;
+  Float_t zlocmin = zloc-dz;
+  Float_t zlocmax = zloc+dz;
+  Float_t xlocmin = xloc-dy;
+  Float_t xlocmax = xloc+dy;
+  Int_t chipsInRoad[100];
+
+  // check if road goes out of detector
+  Bool_t touchNeighbourDet=kFALSE; 
+  if (TMath::Abs(xlocmin)>0.5*detSizeX) {xlocmin=-0.4999*detSizeX; touchNeighbourDet=kTRUE;} 
+  if (TMath::Abs(xlocmax)>0.5*detSizeX) {xlocmax=+0.4999*detSizeX; touchNeighbourDet=kTRUE;} 
+  if (TMath::Abs(zlocmin)>0.5*detSizeZ) {zlocmin=-0.4999*detSizeZ; touchNeighbourDet=kTRUE;} 
+  if (TMath::Abs(zlocmax)>0.5*detSizeZ) {zlocmax=+0.4999*detSizeZ; touchNeighbourDet=kTRUE;} 
+  AliDebug(2,Form("layer %d det %d zmim zmax %f %f xmin xmax %f %f   %f %f",ilayer,idet,zlocmin,zlocmax,xlocmin,xlocmax,detSizeZ,detSizeX));
+
+  // check if this detector is bad
+  if (det.IsBad()) {
+    AliDebug(2,Form("lay %d  bad detector %d",ilayer,idet));
+    if(!touchNeighbourDet) {
+      return 2; // all detectors in road are bad
+    } else { 
+      return 3; // at least one is bad
+    }
+  }
+
+  Int_t nChipsInRoad = segm->GetChipsInLocalWindow(chipsInRoad,zlocmin,zlocmax,xlocmin,xlocmax);
+  AliDebug(2,Form("lay %d nChipsInRoad %d",ilayer,nChipsInRoad));
+  if (!nChipsInRoad) return 0;
+
+  Bool_t anyBad=kFALSE,anyGood=kFALSE;
+  for (Int_t iCh=0; iCh<nChipsInRoad; iCh++) {
+    if (chipsInRoad[iCh]<0 || chipsInRoad[iCh]>det.GetNChips()-1) continue;
+    AliDebug(2,Form("  chip %d bad %d",chipsInRoad[iCh],(Int_t)det.IsChipBad(chipsInRoad[iCh])));
+    if (det.IsChipBad(chipsInRoad[iCh])) {
+      anyBad=kTRUE;
+    } else {
+      anyGood=kTRUE;
+    } 
+  }
+
+  if (!anyGood) {
+    if(!touchNeighbourDet) {
+      AliDebug(2,"all bad in road");
+      return 2;  // all chips in road are bad
+    } else {
+      return 3; // at least a bad chip in road
+    }
+  }
+
+  if (anyBad) {
+    AliDebug(2,"at least a bad in road");
+    return 3; // at least a bad chip in road
+  } 
+
+
+  if (!AliITSReconstructor::GetRecoParam()->GetUseSingleBadChannelsFromOCDB()
+      || !noClusters) return 0;
+
+  // There are no clusters in road: check if there is at least 
+  // a bad SPD pixel or SDD anode or SSD strips on both sides
+
+  Int_t idetInITS=idet;
+  for(Int_t l=0;l<ilayer;l++) idetInITS+=AliITSgeomTGeo::GetNLadders(l+1)*AliITSgeomTGeo::GetNDetectors(l+1);
+
+  if (fITSChannelStatus->AnyBadInRoad(idetInITS,zlocmin,zlocmax,xlocmin,xlocmax)) {
+    AliDebug(2,Form("Bad channel in det %d of layer %d\n",idet,ilayer));
+    return 4;
+  }
+  //if (fITSChannelStatus->FractionOfBadInRoad(idet,zlocmin,zlocmax,xlocmin,xlocmax) > AliITSReconstructor::GetRecoParam()->GetMinFractionOfBadInRoad()) return 3;
+
+  return 0;
+}
+//------------------------------------------------------------------------
+Bool_t AliITStrackerMI::LocalModuleCoord(Int_t ilayer,Int_t idet,
+                                      const AliITStrackMI *track,
+                                      Float_t &xloc,Float_t &zloc) const {
+  //-----------------------------------------------------------------
+  // Gives position of track in local module ref. frame
+  //-----------------------------------------------------------------
+
+  xloc=0.; 
+  zloc=0.;
+
+  if(idet<0) return kTRUE; // track out of z acceptance of layer
+
+  Int_t ndet=AliITSgeomTGeo::GetNDetectors(ilayer+1); // layers from 1 to 6 
+
+  Int_t lad = Int_t(idet/ndet) + 1;
+
+  Int_t det = idet - (lad-1)*ndet + 1;
+
+  Double_t xyzGlob[3],xyzLoc[3];
+
+  AliITSdetector &detector = fgLayers[ilayer].GetDetector(idet);
+  // take into account the misalignment: xyz at real detector plane
+  if(!track->GetXYZAt(detector.GetRmisal(),GetBz(),xyzGlob)) return kFALSE;
+
+  if(!AliITSgeomTGeo::GlobalToLocal(ilayer+1,lad,det,xyzGlob,xyzLoc)) return kFALSE;
+
+  xloc = (Float_t)xyzLoc[0];
+  zloc = (Float_t)xyzLoc[2];
+
+  return kTRUE;
+}
+//------------------------------------------------------------------------
+//------------------------------------------------------------------------
+Bool_t AliITStrackerMI::IsOKForPlaneEff(const AliITStrackMI* track, const Int_t *clusters, Int_t ilayer) const {
+//
+// Method to be optimized further: 
+// Aim: decide whether a track can be used for PlaneEff evaluation
+//      the decision is taken based on the track quality at the layer under study
+//      no information on the clusters on this layer has to be used
+//      The criterium is to reject tracks at boundaries between basic block (e.g. SPD chip)
+//      the cut is done on number of sigmas from the boundaries
+//
+//  Input: Actual track, layer [0,5] under study
+//  Output: none
+//  Return: kTRUE if this is a good track
+//
+// it will apply a pre-selection to obtain good quality tracks.  
+// Here also  you will have the possibility to put a control on the 
+// impact point of the track on the basic block, in order to exclude border regions 
+// this will be done by calling a proper method of the AliITSPlaneEff class.  
+//
+// input: AliITStrackMI* track, ilayer= layer number [0,5]
+// return: Bool_t   -> kTRUE if usable track, kFALSE if not usable. 
+//
+  Int_t index[AliITSgeomTGeo::kNLayers];
+  Int_t k;
+  for (k=0; k<AliITSgeomTGeo::GetNLayers(); k++) index[k]=-1;
+  //
+  for (k=0; k<AliITSgeomTGeo::GetNLayers(); k++) {
+    index[k]=clusters[k];
+  }
+
+  if(!fPlaneEff)
+    {AliWarning("IsOKForPlaneEff: null pointer to AliITSPlaneEff"); return kFALSE;}
+  AliITSlayer &layer=fgLayers[ilayer];
+  Double_t r=layer.GetR();
+  AliITStrackMI tmp(*track);
+
+// require a minimal number of cluster in other layers and eventually clusters in closest layers 
+  Int_t ncl_out=0; Int_t ncl_in=0;
+  for(Int_t lay=AliITSgeomTGeo::kNLayers-1;lay>ilayer;lay--) { // count n. of cluster in outermost layers
+ AliDebug(2,Form("trak=%d  lay=%d  ; index=%d ESD label= %d",tmp.GetLabel(),lay,
+                    tmp.GetClIndex(lay),((AliESDtrack*)tmp.GetESDtrack())->GetLabel())) ;
+   // if (tmp.GetClIndex(lay)>=0) ncl_out++;
+if(index[lay]>=0)ncl_out++;
+  }
+  for(Int_t lay=ilayer-1; lay>=0;lay--) { // count n. of cluster in innermost layers
+    AliDebug(2,Form("trak=%d  lay=%d  ; index=%d ESD label= %d",tmp.GetLabel(),lay,
+                    tmp.GetClIndex(lay),((AliESDtrack*)tmp.GetESDtrack())->GetLabel())) ;
+   if (index[lay]>=0) ncl_in++; 
+  }
+  Int_t ncl=ncl_out+ncl_in;
+  Bool_t nextout = kFALSE;
+  if(ilayer==AliITSgeomTGeo::kNLayers-1) nextout=kTRUE; // you are already on the outermost layer
+  else nextout = ((tmp.GetClIndex(ilayer+1)>=0)? kTRUE : kFALSE );
+  Bool_t nextin = kFALSE;
+  if(ilayer==0) nextin=kTRUE; // you are already on the innermost layer
+  else nextin = ((index[ilayer-1]>=0)? kTRUE : kFALSE );
+  // maximum number of missing clusters allowed in outermost layers
+  if(ncl_out<AliITSgeomTGeo::kNLayers-(ilayer+1)-AliITSReconstructor::GetRecoParam()->GetMaxMissingClustersOutPlaneEff()) 
+     return kFALSE; 
+  // maximum number of missing clusters allowed (both in innermost and in outermost layers)
+  if(ncl<AliITSgeomTGeo::kNLayers-1-AliITSReconstructor::GetRecoParam()->GetMaxMissingClustersPlaneEff()) 
+     return kFALSE; 
+  if(AliITSReconstructor::GetRecoParam()->GetRequireClusterInOuterLayerPlaneEff() && !nextout)  return kFALSE;
+  if(AliITSReconstructor::GetRecoParam()->GetRequireClusterInInnerLayerPlaneEff() && !nextin)   return kFALSE;
+  if(tmp.Pt() < AliITSReconstructor::GetRecoParam()->GetMinPtPlaneEff()) return kFALSE;
+ //  if(AliITSReconstructor::GetRecoParam()->GetOnlyConstraintPlaneEff()  && !tmp.GetConstrain()) return kFALSE;
+
+// detector number
+  Double_t phi,z;
+  if (!tmp.GetPhiZat(r,phi,z)) return kFALSE;
+  Int_t idet=layer.FindDetectorIndex(phi,z);
+  if(idet<0) { AliInfo(Form("cannot find detector"));
+    return kFALSE;}
+
+  // here check if it has good Chi Square.
+
+  //propagate to the intersection with the detector plane
+  const AliITSdetector &det=layer.GetDetector(idet);
+  if (!tmp.Propagate(det.GetPhi(),det.GetR())) return kFALSE;
+
+  Float_t locx; //
+  Float_t locz; //
+  if(!LocalModuleCoord(ilayer,idet,&tmp,locx,locz)) return kFALSE;
+  UInt_t key=fPlaneEff->GetKeyFromDetLocCoord(ilayer,idet,locx,locz);
+  if(key>fPlaneEff->Nblock()) return kFALSE;
+  Float_t blockXmn,blockXmx,blockZmn,blockZmx;
+  if (!fPlaneEff->GetBlockBoundaries(key,blockXmn,blockXmx,blockZmn,blockZmx)) return kFALSE;
+  //***************
+  // DEFINITION OF SEARCH ROAD FOR accepting a track
+  //
+  Double_t nsigx=AliITSReconstructor::GetRecoParam()->GetNSigXFromBoundaryPlaneEff();
+  Double_t nsigz=AliITSReconstructor::GetRecoParam()->GetNSigZFromBoundaryPlaneEff();
+  Double_t dx=nsigx*TMath::Sqrt(tmp.GetSigmaY2());  // those are precisions in the tracking reference system
+  Double_t dz=nsigz*TMath::Sqrt(tmp.GetSigmaZ2());  // Use it also for the module reference system, as it is
+                                                    // done for RecPoints
+
+  // exclude tracks at boundary between detectors
+  //Double_t boundaryWidth=AliITSRecoParam::GetBoundaryWidthPlaneEff();
+  Double_t boundaryWidth=0; // for the time being hard-wired, later on from AliITSRecoParam
+  AliDebug(2,Form("Tracking: track impact x=%f, y=%f, z=%f",tmp.GetX(), tmp.GetY(), tmp.GetZ()));
+  AliDebug(2,Form("Local:    track impact x=%f, z=%f",locx,locz));
+  AliDebug(2,Form("Search Road. Tracking: dy=%f , dz=%f",dx,dz));
+  if ( (locx-dx < blockXmn+boundaryWidth) ||
+       (locx+dx > blockXmx-boundaryWidth) ||
+       (locz-dz < blockZmn+boundaryWidth) ||
+       (locz+dz > blockZmx-boundaryWidth) ) return kFALSE;
+  return kTRUE;
+}
+//------------------------------------------------------------------------
+void AliITStrackerMI::UseTrackForPlaneEff(const AliITStrackMI* track, Int_t ilayer) {
+//
+// This Method has to be optimized! For the time-being it uses the same criteria
+// as those used in the search of extra clusters for overlapping modules.
+//
+// Method Purpose: estabilish whether a track has produced a recpoint or not
+//                 in the layer under study (For Plane efficiency)
+//
+// inputs: AliITStrackMI* track  (pointer to a usable track)
+// outputs: none
+// side effects: update (by 1 count) the Plane Efficiency statistics of the basic block
+//               traversed by this very track. In details:
+//               - if a cluster can be associated to the track then call
+//                  AliITSPlaneEff::UpDatePlaneEff(key,kTRUE);
+//               - if not, the AliITSPlaneEff::UpDatePlaneEff(key,kFALSE) is called
+//
+  if(!fPlaneEff)
+    {AliWarning("UseTrackForPlaneEff: null pointer to AliITSPlaneEff"); return;}
+  AliITSlayer &layer=fgLayers[ilayer];
+  Double_t r=layer.GetR();
+  AliITStrackMI tmp(*track);
+
+// detector number
+  Double_t phi,z;
+  if (!tmp.GetPhiZat(r,phi,z)) return;
+  Int_t idet=layer.FindDetectorIndex(phi,z);
+
+  if(idet<0) { AliInfo(Form("cannot find detector"));
+    return;}
+
+
+//propagate to the intersection with the detector plane
+  const AliITSdetector &det=layer.GetDetector(idet);
+  if (!tmp.Propagate(det.GetPhi(),det.GetR())) return;
+
+
+//***************
+// DEFINITION OF SEARCH ROAD FOR CLUSTERS SELECTION
+//
+  Double_t dz=AliITSReconstructor::GetRecoParam()->GetNSigmaRoadZ()*
+                    TMath::Sqrt(tmp.GetSigmaZ2() +
+                    AliITSReconstructor::GetRecoParam()->GetNSigmaZLayerForRoadZ()*
+                    AliITSReconstructor::GetRecoParam()->GetNSigmaZLayerForRoadZ()*
+                    AliITSReconstructor::GetRecoParam()->GetSigmaZ2(ilayer));
+  Double_t dy=AliITSReconstructor::GetRecoParam()->GetNSigmaRoadY()*
+                    TMath::Sqrt(tmp.GetSigmaY2() +
+                    AliITSReconstructor::GetRecoParam()->GetNSigmaYLayerForRoadY()*
+                    AliITSReconstructor::GetRecoParam()->GetNSigmaYLayerForRoadY()*
+                    AliITSReconstructor::GetRecoParam()->GetSigmaY2(ilayer));
+
+// road in global (rphi,z) [i.e. in tracking ref. system]
+  Double_t zmin = tmp.GetZ() - dz;
+  Double_t zmax = tmp.GetZ() + dz;
+  Double_t ymin = tmp.GetY() + r*det.GetPhi() - dy;
+  Double_t ymax = tmp.GetY() + r*det.GetPhi() + dy;
+
+// select clusters in road
+  layer.SelectClusters(zmin,zmax,ymin,ymax);
+
+// Define criteria for track-cluster association
+  Double_t msz = tmp.GetSigmaZ2() +
+  AliITSReconstructor::GetRecoParam()->GetNSigmaZLayerForRoadZ()*
+  AliITSReconstructor::GetRecoParam()->GetNSigmaZLayerForRoadZ()*
+  AliITSReconstructor::GetRecoParam()->GetSigmaZ2(ilayer);
+  Double_t msy = tmp.GetSigmaY2() +
+  AliITSReconstructor::GetRecoParam()->GetNSigmaYLayerForRoadY()*
+  AliITSReconstructor::GetRecoParam()->GetNSigmaYLayerForRoadY()*
+  AliITSReconstructor::GetRecoParam()->GetSigmaY2(ilayer);
+  if (tmp.GetConstrain()) {
+    msz *= AliITSReconstructor::GetRecoParam()->GetNSigma2RoadZC();
+    msy *= AliITSReconstructor::GetRecoParam()->GetNSigma2RoadYC();
+  }  else {
+    msz *= AliITSReconstructor::GetRecoParam()->GetNSigma2RoadZNonC();
+    msy *= AliITSReconstructor::GetRecoParam()->GetNSigma2RoadYNonC();
+  }
+  msz = 1./msz; // 1/RoadZ^2
+  msy = 1./msy; // 1/RoadY^2
+//
+
+  const AliITSRecPoint *cl=0; Int_t clidx=-1, ci=-1;
+  Int_t idetc=-1;
+  Double_t chi2trkcl=1000.*AliITSReconstructor::GetRecoParam()->GetMaxChi2();
+  //Double_t  tolerance=0.2;
+  /*while ((cl=layer.GetNextCluster(clidx))!=0) {
+    idetc = cl->GetDetectorIndex();
+    if(idet!=idetc) continue;
+    //Int_t ilay = cl->GetLayer();
+
+    if (TMath::Abs(tmp.GetZ() - cl->GetZ()) > tolerance) continue;
+    if (TMath::Abs(tmp.GetY() - cl->GetY()) > tolerance) continue;
+
+    Double_t chi2=tmp.GetPredictedChi2(cl);
+    if (chi2<chi2trkcl) { chi2trkcl=chi2; ci=clidx; }
+  }*/
+  Float_t locx; //
+  Float_t locz; //
+  if(!LocalModuleCoord(ilayer,idet,&tmp,locx,locz)) return;
+//
+  AliDebug(2,Form("ilayer= %d, idet=%d, x= %f, z=%f",ilayer,idet,locx,locz));
+  UInt_t key=fPlaneEff->GetKeyFromDetLocCoord(ilayer,idet,locx,locz);
+  if(key>fPlaneEff->Nblock()) return;
+  Bool_t found=kFALSE;
+  //if (ci>=0) {
+  Double_t chi2;
+  while ((cl=layer.GetNextCluster(clidx))!=0) {
+    idetc = cl->GetDetectorIndex();
+    if(idet!=idetc) continue;
+    // here real control to see whether the cluster can be associated to the track.
+    // cluster not associated to track
+    if ( (tmp.GetZ()-cl->GetZ())*(tmp.GetZ()-cl->GetZ())*msz +
+         (tmp.GetY()-cl->GetY())*(tmp.GetY()-cl->GetY())*msy   > 1. ) continue;
+    // calculate track-clusters chi2
+    chi2 = GetPredictedChi2MI(&tmp,cl,ilayer); // note that this method change track tmp
+                                               // in particular, the error associated to the cluster 
+    //Double_t chi2 = tmp.GetPredictedChi(cl); // this method does not change track tmp
+    // chi2 cut
+    if (chi2 > AliITSReconstructor::GetRecoParam()->GetMaxChi2s(ilayer)) continue;
+    found=kTRUE;
+    if (chi2<chi2trkcl) { chi2trkcl=chi2; ci=clidx; } // this just to trace which cluster is selected
+   // track->SetExtraCluster(ilayer,(ilayer<<28)+ci);
+   // track->SetExtraModule(ilayer,idetExtra);
+  }
+  if(!fPlaneEff->UpDatePlaneEff(found,key))
+       AliWarning(Form("UseTrackForPlaneEff: cannot UpDate PlaneEff for key=%d",key));
+  if(fPlaneEff->GetCreateHistos()&&  AliITSReconstructor::GetRecoParam()->GetHistoPlaneEff()) {
+    Float_t tr[4]={99999.,99999.,9999.,9999.};    // initialize to high values 
+    Float_t clu[4]={-99999.,-99999.,9999.,9999.}; // (in some cases GetCov fails) 
+    Int_t cltype[2]={-999,-999};
+                                                          // and the module
+
+Float_t AngleModTrack[3]={99999.,99999.,99999.}; // angles (phi, z and "absolute angle") between the track and the mormal to the module (see below)
+
+    tr[0]=locx;
+    tr[1]=locz;
+    tr[2]=TMath::Sqrt(tmp.GetSigmaY2());  // those are precisions in the tracking reference system
+    tr[3]=TMath::Sqrt(tmp.GetSigmaZ2());  // Use it also for the module reference system, as it is
+
+    if (found){
+      clu[0]=layer.GetCluster(ci)->GetDetLocalX();
+      clu[1]=layer.GetCluster(ci)->GetDetLocalZ();
+      cltype[0]=layer.GetCluster(ci)->GetNy();
+      cltype[1]=layer.GetCluster(ci)->GetNz();
+     
+     // Without the following 6 lines you would retrieve the nominal error of a cluster (e.g. for the SPD:
+     //  X->50/sqrt(12)=14 micron   Z->450/sqrt(12)= 120 micron) 
+     // Within AliTrackerMI/AliTrackMI the error on the cluster is associated to the AliITStrackMI (fSigmaY,Z)
+     // It is computed properly by calling the method 
+     // AliITStrackerMI::GetPredictedChi2MI(AliITStrackMI* track, const AliITSRecPoint *cluster,Int_t layer)
+     // T
+     //Double_t x=0.5*(tmp.GetX()+layer.GetCluster(ci)->GetX()); // Take into account the mis-alignment
+      //if (tmp.PropagateTo(x,0.,0.)) {
+        chi2=GetPredictedChi2MI(&tmp,layer.GetCluster(ci),ilayer);
+        AliCluster c(*layer.GetCluster(ci));
+        c.SetSigmaY2(tmp.GetSigmaY(ilayer)*tmp.GetSigmaY(ilayer));
+        c.SetSigmaZ2(tmp.GetSigmaZ(ilayer)*tmp.GetSigmaZ(ilayer));
+        //if (layer.GetCluster(ci)->GetGlobalCov(cov))  // by using this, instead, you got nominal cluster errors
+        clu[2]=TMath::Sqrt(c.GetSigmaY2());
+        clu[3]=TMath::Sqrt(c.GetSigmaZ2());
+      //}
+    }
+  // Compute the angles between the track and the module
+      // compute the angle "in phi direction", i.e. the angle in the transverse plane 
+      // between the normal to the module and the projection (in the transverse plane) of the 
+      // track trajectory
+    // tgphi and tglambda of the track in tracking frame with alpha=det.GetPhi
+    Float_t tgl = tmp.GetTgl();
+    Float_t phitr   = tmp.GetSnp();
+    phitr = TMath::ASin(phitr);
+    Int_t volId = AliGeomManager::LayerToVolUIDSafe(ilayer+1 ,idet );
+
+    Double_t tra[3]; AliGeomManager::GetOrigTranslation(volId,tra);
+    Double_t rot[9]; AliGeomManager::GetOrigRotation(volId,rot);
+   Double_t alpha =0.;
+    alpha = tmp.GetAlpha();
+    Double_t phiglob = alpha+phitr;
+    Double_t p[3];
+    p[0] = TMath::Cos(phiglob);
+    p[1] = TMath::Sin(phiglob);
+    p[2] = tgl;
+    TVector3 pvec(p[0],p[1],p[2]);
+    TVector3 normvec(rot[1],rot[4],rot[7]);
+    Double_t angle = pvec.Angle(normvec);
+
+    if(angle>0.5*TMath::Pi()) angle = (TMath::Pi()-angle);
+    angle *= 180./TMath::Pi();
+
+    //Trasverse Plane
+    TVector3 pt(p[0],p[1],0);
+    TVector3 normt(rot[1],rot[4],0);
+    Double_t anglet = pt.Angle(normt);
+
+    Double_t phiPt = TMath::ATan2(p[1],p[0]);
+    if(phiPt<0)phiPt+=2.*TMath::Pi();
+    Double_t phiNorm = TMath::ATan2(rot[4],rot[1]);
+    if(phiNorm<0) phiNorm+=2.*TMath::Pi();
+    if(anglet>0.5*TMath::Pi()) anglet = (TMath::Pi()-anglet);
+    if(phiNorm>phiPt) anglet*=-1.;// pt-->normt  clockwise: anglet>0
+    if((phiNorm-phiPt)>TMath::Pi()) anglet*=-1.;
+    anglet *= 180./TMath::Pi();
+
+     AngleModTrack[2]=(Float_t) angle;
+     AngleModTrack[0]=(Float_t) anglet;
+     // now the "angle in z" (much easier, i.e. the angle between the z axis and the track momentum + 90)
+    AngleModTrack[1]=TMath::ACos(tgl/TMath::Sqrt(tgl*tgl+1.));
+    AngleModTrack[1]-=TMath::Pi()/2.; // range of angle is -pi/2 , pi/2
+    AngleModTrack[1]*=180./TMath::Pi(); // in degree
+
+      fPlaneEff->FillHistos(key,found,tr,clu,cltype,AngleModTrack);
+  }
+return;
+}