]> git.uio.no Git - u/mrichter/AliRoot.git/blobdiff - TPC/AliTPC.cxx
fixing some minor coverty reports
[u/mrichter/AliRoot.git] / TPC / AliTPC.cxx
index e0d7bd71937e3ab0187c71628ba1f156d6c0b908..19f97c717817f6a46a3782d257bcc39733ad46a7 100644 (file)
@@ -1,3 +1,20 @@
+/**************************************************************************
+ * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
+ *                                                                        *
+ * Author: The ALICE Off-line Project.                                    *
+ * Contributors are mentioned in the code where appropriate.              *
+ *                                                                        *
+ * Permission to use, copy, modify and distribute this software and its   *
+ * documentation strictly for non-commercial purposes is hereby granted   *
+ * without fee, provided that the above copyright notice appears in all   *
+ * copies and that both the copyright notice and this permission notice   *
+ * appear in the supporting documentation. The authors make no claims     *
+ * about the suitability of this software for any purpose. It is          *
+ * provided "as is" without express or implied warranty.                  *
+ **************************************************************************/
+
+/* $Id$ */
+
 ///////////////////////////////////////////////////////////////////////////////
 //                                                                           //
 //  Time Projection Chamber                                                  //
 //                                                                           //
 //Begin_Html
 /*
-<img src="gif/AliTPCClass.gif">
+<img src="picts/AliTPCClass.gif">
 */
 //End_Html
 //                                                                           //
-//                                                                           //
+//                                                                          //
 ///////////////////////////////////////////////////////////////////////////////
 
+//
+
+#include <Riostream.h>
+#include <stdlib.h>
+
+#include <TF2.h>
+#include <TFile.h>  
+#include <TGeoGlobalMagField.h>
+#include <TInterpreter.h>
 #include <TMath.h>
+#include <TMatrixF.h>
+#include <TObjectTable.h>
+#include <TParticle.h>
+#include <TROOT.h>
 #include <TRandom.h>
+#include <TStopwatch.h>
+#include <TString.h>
+#include <TSystem.h>     
+#include <TTree.h>
 #include <TVector.h>
-#include <TGeometry.h>
-#include <TNode.h>
-#include <TTUBS.h>
-#include <TObjectTable.h>
-#include "GParticle.h"
-#include "AliTPC.h"
+#include <TVirtualMC.h>
+#include <TParameter.h>
+
+#include "AliDigits.h"
+#include "AliMagF.h"
 #include "AliRun.h"
-#include <iostream.h>
-#include <fstream.h>
+#include "AliRunLoader.h"
+#include "AliSimDigits.h"
+#include "AliTPC.h"
+#include "AliTPC.h"
+#include "AliTPCDigitsArray.h"
+#include "AliTPCLoader.h"
+#include "AliTPCPRF2D.h"
+#include "AliTPCParamSR.h"
+#include "AliTPCRF1D.h"
+#include "AliTPCTrackHitsV2.h"
+#include "AliTrackReference.h"
 #include "AliMC.h"
+#include "AliStack.h"
+#include "AliTPCDigitizer.h"
+#include "AliTPCBuffer.h"
+#include "AliTPCDDLRawData.h"
+#include "AliLog.h"
+#include "AliTPCcalibDB.h"
+#include "AliTPCCalPad.h"
+#include "AliTPCCalROC.h"
+#include "AliTPCExB.h"
+#include "AliRawReader.h"
+#include "AliTPCRawStreamV3.h"
+#include "TTreeStream.h"
 
 ClassImp(AliTPC) 
-
 //_____________________________________________________________________________
-AliTPC::AliTPC()
+  AliTPC::AliTPC():AliDetector(),
+                  fDefaults(0),
+                  fSens(0),
+                  fNsectors(0),
+                  fDigitsArray(0),
+                  fTPCParam(0),
+                  fTrackHits(0),
+                  fHitType(0),
+                  fDigitsSwitch(0),
+                  fSide(0),
+                   fPrimaryIonisation(0),
+                  fNoiseDepth(0),
+                  fNoiseTable(0),
+                  fCurrentNoise(0),
+                  fActiveSectors(0),
+                   fGainFactor(1.),
+                   fDebugStreamer(0),
+                   fLHCclockPhaseSw(0)
+
 {
   //
   // Default constructor
   //
   fIshunt   = 0;
-  fClusters = 0;
-  fHits     = 0;
-  fDigits   = 0;
-  fTracks   = 0;
-  fNsectors = 0;
-  fNtracks  = 0;
-  fNclusters= 0;
+  //  fTrackHitsOld = 0;   
+#if ROOT_VERSION_CODE >= ROOT_VERSION(4,0,1)
+  fHitType = 4; // ROOT containers
+#else
+  fHitType = 2; //default CONTAINERS - based on ROOT structure
+#endif 
 }
  
 //_____________________________________________________________________________
 AliTPC::AliTPC(const char *name, const char *title)
-      : AliDetector(name,title)
+  : AliDetector(name,title),
+                   fDefaults(0),
+                  fSens(0),
+                  fNsectors(0),
+                  fDigitsArray(0),
+                  fTPCParam(0),
+                  fTrackHits(0),
+                  fHitType(0),
+                  fDigitsSwitch(0),
+                  fSide(0),
+                   fPrimaryIonisation(0),
+                  fNoiseDepth(0),
+                  fNoiseTable(0),
+                  fCurrentNoise(0),
+                   fActiveSectors(0),
+                   fGainFactor(1.),
+                   fDebugStreamer(0),
+                   fLHCclockPhaseSw(0)
+                  
 {
   //
   // Standard constructor
@@ -57,1404 +146,2054 @@ AliTPC::AliTPC(const char *name, const char *title)
   //
   // Initialise arrays of hits and digits 
   fHits     = new TClonesArray("AliTPChit",  176);
-  fDigits   = new TClonesArray("AliTPCdigit",10000);
+  gAlice->GetMCApp()->AddHitList(fHits); 
   //
-  // Initialise counters
-  fClusters = 0;
-  fTracks   = 0;
-  fNsectors = 72;
-  fNtracks  = 0;
-  fNclusters= 0;
-  fDigitsIndex = new Int_t[fNsectors+1];
-  fClustersIndex = new Int_t[fNsectors+1];
+  fTrackHits = new AliTPCTrackHitsV2;  
+  fTrackHits->SetHitPrecision(0.002);
+  fTrackHits->SetStepPrecision(0.003);  
+  fTrackHits->SetMaxDistance(100);
+
+  //fTrackHitsOld = new AliTPCTrackHits;  //MI - 13.09.2000
+  //fTrackHitsOld->SetHitPrecision(0.002);
+  //fTrackHitsOld->SetStepPrecision(0.003);  
+  //fTrackHitsOld->SetMaxDistance(100); 
+
+
+#if ROOT_VERSION_CODE >= ROOT_VERSION(4,0,1)
+  fHitType = 4; // ROOT containers
+#else
+  fHitType = 2;
+#endif
+
+
+
   //
   fIshunt     =  0;
   //
   // Initialise color attributes
-  SetMarkerColor(kYellow);
-}
+  //PH SetMarkerColor(kYellow);
 
-//_____________________________________________________________________________
-AliTPC::~AliTPC()
-{
   //
-  // TPC destructor
+  //  Set TPC parameters
   //
-  fIshunt   = 0;
-  delete fHits;
-  delete fDigits;
-  delete fClusters;
-  delete fTracks;
-  if (fDigitsIndex)   delete [] fDigitsIndex;
-  if (fClustersIndex) delete [] fClustersIndex;
-}
 
-//_____________________________________________________________________________
-void AliTPC::AddCluster(Float_t *hits, Int_t *tracks)
-{
-  //
-  // Add a simulated cluster to the list
-  //
-  if(!fClusters) fClusters=new TClonesArray("AliTPCcluster",10000);
-  TClonesArray &lclusters = *fClusters;
-  new(lclusters[fNclusters++]) AliTPCcluster(hits,tracks);
+
+  if (!strcmp(title,"Default")) {       
+    //fTPCParam = new AliTPCParamSR;
+    fTPCParam = AliTPCcalibDB::Instance()->GetParameters();
+  } else {
+    AliWarning("In Config.C you must set non-default parameters.");
+    fTPCParam=0;
+  }
+
 }
-//_____________________________________________________________________________
-void AliTPC::AddCluster(const AliTPCcluster &c)
-{
+void AliTPC::CreateDebugStremer(){
   //
-  // Add a simulated cluster copy to the list
-  //
-  if(!fClusters) fClusters=new TClonesArray("AliTPCcluster",10000);
-  TClonesArray &lclusters = *fClusters;
-  new(lclusters[fNclusters++]) AliTPCcluster(c);
+  // Create Debug streamer to check simulation
+  // 
+  fDebugStreamer = new TTreeSRedirector("TPCSimdebug.root");
 }
 //_____________________________________________________________________________
-void AliTPC::AddDigit(Int_t *tracks, Int_t *digits)
+AliTPC::~AliTPC()
 {
   //
-  // Add a TPC digit to the list
+  // TPC destructor
   //
-  TClonesArray &ldigits = *fDigits;
-  new(ldigits[fNdigits++]) AliTPCdigit(tracks,digits);
+
+  fIshunt   = 0;
+  delete fHits;
+  delete fDigits;
+  //delete fTPCParam;
+  delete fTrackHits; //MI 15.09.2000
+  //  delete fTrackHitsOld; //MI 10.12.2001
+  
+  fDigitsArray = 0x0;
+  delete [] fNoiseTable;
+  delete [] fActiveSectors;
+  if (fDebugStreamer) delete fDebugStreamer;
 }
+
 //_____________________________________________________________________________
 void AliTPC::AddHit(Int_t track, Int_t *vol, Float_t *hits)
 {
   //
   // Add a hit to the list
   //
-  TClonesArray &lhits = *fHits;
-  new(lhits[fNhits++]) AliTPChit(fIshunt,track,vol,hits);
-}
-//_____________________________________________________________________________
-void AliTPC::AddTrack(Float_t *hits)
-{
-  //
-  // Add a track to the list of tracks
-  //
-  TClonesArray &ltracks = *fTracks;
-  new(ltracks[fNtracks++]) AliTPCtrack(hits);
+  if (fHitType&1){
+    TClonesArray &lhits = *fHits;
+    new(lhits[fNhits++]) AliTPChit(fIshunt,track,vol,hits);
+  }
+  if (fHitType>1)
+    AddHit2(track,vol,hits);
 }
 
 //_____________________________________________________________________________
-void AliTPC::AddTrack(const AliTPCtrack& t)
+void AliTPC::CreateMaterials()
 {
-  //
-  // Add a track copy to the list of tracks
-  //
-  if(!fTracks) fTracks=new TClonesArray("AliTPCtrack",10000);
-  TClonesArray &ltracks = *fTracks;
-  new(ltracks[fNtracks++]) AliTPCtrack(t);
-}
+  //-----------------------------------------------
+  // Create Materials for for TPC simulations
+  //-----------------------------------------------
 
-//_____________________________________________________________________________
-void AliTPC::BuildGeometry()
-{
-  //
-  // Build TPC ROOT TNode geometry for the event display
-  //
-  TNode *Node, *Top;
-  TTUBS *tubs;
-  Int_t i;
-  const int kColorTPC=19;
-  char name[5], title[18];
-  const Double_t kDegrad=TMath::Pi()/180;
-  const Double_t loAng=30;
-  const Double_t hiAng=15;
-  const Int_t nLo = Int_t (360/loAng+0.5);
-  const Int_t nHi = Int_t (360/hiAng+0.5);
-  const Double_t loCorr = 1/TMath::Cos(0.5*loAng*kDegrad);
-  const Double_t hiCorr = 1/TMath::Cos(0.5*hiAng*kDegrad);
-  //
-  // Get ALICE top node
-  Top=gAlice->GetGeometry()->GetNode("alice");
-  //
-  // Inner sectors
-  for(i=0;i<nLo;i++) {
-    sprintf(name,"LS%2.2d",i);
-    sprintf(title,"TPC low sector %d",i);
-    tubs = new TTUBS(name,title,"void",88*loCorr,136*loCorr,250,loAng*(i-0.5),loAng*(i+0.5));
-    tubs->SetNumberOfDivisions(1);
-    Top->cd();
-    Node = new TNode(name,title,name,0,0,0,"");
-    Node->SetLineColor(kColorTPC);
-    fNodes->Add(Node);
-  }
-  // Outer sectors
-  for(i=0;i<nHi;i++) {
-    sprintf(name,"US%2.2d",i);
-    sprintf(title,"TPC upper sector %d",i);
-    tubs = new TTUBS(name,title,"void",142*hiCorr,250*hiCorr,250,hiAng*(i-0.5),hiAng*(i+0.5));
-    tubs->SetNumberOfDivisions(1);
-    Top->cd();
-    Node = new TNode(name,title,name,0,0,0,"");
-    Node->SetLineColor(kColorTPC);
-    fNodes->Add(Node);
-  }
-}
+  //-----------------------------------------------------------------
+  // Origin: Marek Kowalski  IFJ, Krakow, Marek.Kowalski@ifj.edu.pl
+  //-----------------------------------------------------------------
+
+   Int_t iSXFLD=((AliMagF*)TGeoGlobalMagField::Instance()->GetField())->Integ();
+  Float_t sXMGMX=((AliMagF*)TGeoGlobalMagField::Instance()->GetField())->Max();
+
+  Float_t amat[5]; // atomic numbers
+  Float_t zmat[5]; // z
+  Float_t wmat[5]; // proportions
+
+  Float_t density;
  
 
-//_____________________________________________________________________________
-void AliTPC::CreateList(Int_t *tracks,Float_t signal[][MAXTPCTBK+1],
-                       Int_t ntr,Int_t time)
-{
+
+  //***************** Gases *************************
+
+  //--------------------------------------------------------------
+  // gases - air and CO2
+  //--------------------------------------------------------------
+
+  // CO2
+
+  amat[0]=12.011;
+  amat[1]=15.9994;
+
+  zmat[0]=6.;
+  zmat[1]=8.;
+
+  wmat[0]=0.2729;
+  wmat[1]=0.7271;
+
+  density=0.001754609;
+
+
+  AliMixture(10,"CO2",amat,zmat,density,2,wmat);
   //
-  // Creates list of tracks contributing to a given digit
-  // Only the 3 most significant tracks are taken into account
+  // Air
   //
-  
-  Int_t i,j;
-  
-  for(i=0;i<3;i++) tracks[i]=-1;
-  
+  amat[0]=15.9994;
+  amat[1]=14.007;
   //
-  //  Loop over signals, only 3 times
+  zmat[0]=8.;
+  zmat[1]=7.;
   //
-  
-  Float_t qmax;
-  Int_t jmax;
-  Int_t jout[3] = {-1,-1,-1};
+  wmat[0]=0.233;
+  wmat[1]=0.767;
+  //
+  density=0.001205;
 
-  for(i=0;i<3;i++){
-    qmax=0.;
-    jmax=0;
-    
-    for(j=0;j<ntr;j++){
-      
-      if((i == 1 && j == jout[i-1]) 
-        ||(i == 2 && (j == jout[i-1] || j == jout[i-2]))) continue;
-      
-      if(signal[j][time] > qmax) {
-       qmax = signal[j][time];
-       jmax=j;
-      }       
-    } 
-    
-    if(qmax > 0.) {
-      tracks[i]=jmax; 
-      jout[i]=jmax;
-    }
-    
-  } 
+  AliMixture(11,"Air",amat,zmat,density,2,wmat);
   
-  for(i=0;i<3;i++){
-    if(tracks[i] < 0){
-      tracks[i]=0;
-    }
-    else {
-      tracks[i]=(Int_t) signal[tracks[i]][0]; // first element is a track number
-    }
-  }
-}
+  //----------------------------------------------------------------
+  // drift gases 
+  //----------------------------------------------------------------
 
-//_____________________________________________________________________________
-void AliTPC::DigSignal(Int_t isec,Int_t irow,TObjArray *pointer)
-{
-  //
-  // Digitalise TPC signal
-  //
-  Int_t pad_c,n_of_pads;
-  Int_t pad_number;
-  
-  n_of_pads = (isec < 25) ? npads_low[irow] : npads_up[irow];
-  pad_c=(n_of_pads+1)/2; // this is the "central" pad for a row
-
-  Int_t track,idx;
-  Int_t entries;
-  TVector *pp;
-  TVector *ppp;
-  Float_t y,yy,z;
-  Float_t pad_signal = 0;
-  Float_t signal[MAXTPCTBK]; // Integrated signal over all tracks
-  Float_t signal_tr[100][MAXTPCTBK+1]; // contribution from less than 50 tracks
-  Int_t flag; // flag indicating a track contributing to a pad signal
-  
   //
+  // Drift gases 1 - nonsensitive, 2 - sensitive
+  // Ne-CO2-N2 (90-10-5) (volume) values at 20deg and 1 atm.
+  // rho(Ne) = 0.839 g/cm^3, rho(CO2) = 1.842 g/cm^3, rho(N2) = 1.165 g/cm^3
+  // for the calculation - everything is normalized to 1
 
-  Int_t ntracks = pointer->GetEntriesFast();
+  amat[0]= 20.18;
+  amat[1]=12.011;
+  amat[2]=15.9994;
+  amat[3]=14.007;
 
-  if(ntracks == 0) return; // no signal on this row!
-  
-  //--------------------------------------------------------------
-  // For each electron calculate the pad number and the avalanche
-  //             This is only once per pad row
-  //--------------------------------------------------------------
-  
-  TVector **el = new TVector* [ntracks]; // each track is a new vector
+  zmat[0]= 10.; 
+  zmat[1]=6.;
+  zmat[2]=8.;
+  zmat[3]=7.;
 
-  TObjArray *arr = new TObjArray; // array of tracks for this row
-  
-  for(track=0;track<ntracks;track++) {
-    pp = (TVector*) pointer->At(track);
-    entries = pp->GetNrows();
-    el[track] = new TVector(entries-1);
-    TVector &v1 = *el[track];
-    TVector &v2 = *pp;
-    
-    for(idx=0;idx<entries-2;idx+=2)
-      {
-       y=v2(idx+1);
-       yy=TMath::Abs(y);
-       
-       Float_t range=((n_of_pads-1)/2 + 0.5)*pad_pitch_w;
-       //
-       // Pad number and pad range
-       //
-       if(yy < 0.5*pad_pitch_w){
-         pad_number=pad_c;
-       }
-       else if (yy < range){
-         pad_number=(Int_t) ((yy-0.5*pad_pitch_w)/pad_pitch_w +1.);
-         pad_number=(Int_t) (pad_number*TMath::Sign(1.,(double) y)+pad_c);
-       }  
-       else{
-         pad_number=0;
-       }
-       
-       v1(idx) = (Float_t) pad_number;
-       
-       // Avalanche, taking the fluctuations into account
-       
-       Int_t gain_fluct = (Int_t) (-gas_gain*TMath::Log(gRandom->Rndm()));
-       v1(idx+1)= (Float_t) gain_fluct;
-       
-      } // end of loop over electrons
-    
-    arr->Add(el[track]); // add the vector to the array
-    
-  }// end of loop over tracks
-  
-  delete [] el; //  delete an array of pointers
-  
-  //-------------------------------------------------------------
-  //  Calculation of signal for every pad 
-  //-------------------------------------------------------------
+  wmat[0]=0.756992632;
+  wmat[1]=0.056235789;
+  wmat[2]=0.128469474;
+  wmat[3]=0.058395789;
+  density=0.000904929;
 
-  //-------------------------------------------------------------
-  // Loop over pads
-  //-------------------------------------------------------------
+  AliMixture(12,"Ne-CO2-N-1",amat,zmat,density,4,wmat);
+  AliMixture(13,"Ne-CO2-N-2",amat,zmat,density,4,wmat);
+  AliMixture(30,"Ne-CO2-N-3",amat,zmat,density,4,wmat);
+  //----------------------------------------------------------------------
+  //               solid materials
+  //----------------------------------------------------------------------
 
 
-  for(Int_t np=1;np<n_of_pads+1;np++)
-    {
-      for(Int_t l =0;l<MAXTPCTBK;l++) signal[l]=0.; // set signals for this pad to 0
-      
-      for(Int_t k1=0;k1<100;k1++){
-       for(Int_t k2=0;k2<MAXTPCTBK+1;k2++) signal_tr[k1][k2]=0.;
-      }
-      Int_t track_counter=0; 
-      //
-      
-      //---------------------------------------------------------
-      // Loop over tracks
-      // --------------------------------------------------------
-      
-      for(track=0;track<ntracks;track++)
-       {
-          flag = 0;
-          pp = (TVector*) pointer->At(track);
-          ppp = (TVector*) arr->At(track);
-         
-          TVector &v1 = *pp;
-          TVector &v2 = *ppp;
-          
-          entries = pp->GetNrows();
-         
+  // Kevlar C14H22O2N2
 
-         //----------------------------------------------------
-         // Loop over electrons
-         //----------------------------------------------------
-         
-          for(idx=0;idx<entries-2;idx+=2)
-           {
-             
-             pad_number = (Int_t) v2(idx);
-             
-             if(pad_number == 0) continue; // skip electrons outside range
-             
-             Int_t pad_dist = pad_number-np;
-             Int_t abs_dist = TMath::Abs(pad_dist);
-             
-             if(abs_dist > 3) continue; // beyond signal range
-             
-             y=  v1(idx+1);
-             z = v1(idx+2);
-             
-             Float_t dist = y-(pad_number-pad_c)*pad_pitch_w;
-             
-             //----------------------------------------------
-             // Calculate the signal induced on a pad "np"
-             //----------------------------------------------
-             
-             if(pad_dist < 0) dist = -dist;
-             
-             switch((Int_t) abs_dist){
-             case 0 : pad_signal = P4(dist); // electron is on pad "np"
-                          break;
-             case 1 : pad_signal = P3(dist); // electron is 1 pad away
-               break;
-             case 2 : pad_signal = P2(dist); // electron is 2 pads away
-               break;
-             case 3 : pad_signal = P1(dist); // electron is 3 pads away
-             }
-             
-             //---------------------------------
-              //  Multiply by a gas gain
-             //---------------------------------
-             
-              pad_signal=pad_signal*v2(idx+1);
-             
-              flag = 1;
-             
-             
-             //-----------------------------------------------
-             //  Sample the pad signal in time
-             //-----------------------------------------------
-             
-             Float_t t_drift = (z_end-TMath::Abs(z))/v_drift; // drift time
-             
-             Float_t t_offset = t_drift-t_sample*(Int_t)(t_drift/t_sample);   
-             Int_t first_bucket = (Int_t) (t_drift/t_sample+1.); 
-             
-             for(Int_t bucket = 1;bucket<6;bucket++){
-               Float_t time = (bucket-1)*t_sample+t_offset;
-               Int_t time_idx = first_bucket+bucket-1;
-               Float_t ampl = pad_signal*TimeRes(time);
-               if (time_idx > MAXTPCTBK) break; //Y.Belikov
-               if (track_counter >=100) break;  //Y.Belikov
-
-               signal_tr[track_counter][time_idx] += ampl; // single track only
-               signal[time_idx-1] += ampl;  // fill a signal array for this pad
-               
-             } // end of time sampling
-             
-           } // end of loop over electrons for a current track
-         
-         //-----------------------------------------------
-         //  add the track number and update the counter
-         //  if it gave a nonzero contribution to the pad
-         //-----------------------------------------------
-         if(flag != 0 && track_counter < 100){
-          signal_tr[track_counter][0] = v1(0);
-          track_counter++;      // counter is looking at the NEXT track!
-         }
-         
-       } // end of loop over tracks
-      
-      //----------------------------------------------
-      //  Fill the Digits for this pad
-      //----------------------------------------------
-      
-      Int_t tracks[3];
-      Int_t digits[5];
-      
-      digits[0]=isec; // sector number
-      digits[1]=irow+1; // row number
-      digits[2]=np;   // pad number
-      
-      Float_t q;
-      
-      for(Int_t time = 0;time<MAXTPCTBK;time++){
-       digits[3] = time+1; // time bucket
-       
-       q = signal[time];
-       q = gRandom->Gaus(q,sigma_noise); // apply noise
-       
-       q *= (q_el*1.e15); // convert to fC
-       q *= chip_gain; // convert to mV   
-       q *= (adc_sat/dyn_range); // convert to ADC counts
-       
-       if(q < zero_sup) continue; // do not fill "zeros"
-       if(q > adc_sat) q = adc_sat;  // saturation
-       digits[4] = (Int_t) q;                   // ADC counts
-       
-       //--------------------------------------------------
-       //    "Real signal" or electronics noise
-       //--------------------------------------------------
-       
-       if(signal[time] > 0.){
-         
-         //-----------------------------------------------------
-         //  Create a list of tracks contributing to this digit
-         //  If the digit results from a noise, track number is 0
-         //-----------------------------------------------------
-         
-         CreateList(tracks,signal_tr,track_counter,time);
-       }
-       else {
-         for(Int_t ii=0;ii<3;ii++) tracks[ii]=0;
-       }
-       
-       AddDigit(tracks,digits);
-       
-       
-      } // end of digits for this pad
-      
-    } // end of loop over pads
+  amat[0] = 12.011;
+  amat[1] = 1.;
+  amat[2] = 15.999;
+  amat[3] = 14.006;
+
+  zmat[0] = 6.;
+  zmat[1] = 1.;
+  zmat[2] = 8.;
+  zmat[3] = 7.;
+
+  wmat[0] = 14.;
+  wmat[1] = 22.;
+  wmat[2] = 2.;
+  wmat[3] = 2.;
+
+  density = 1.45;
+
+  AliMixture(14,"Kevlar",amat,zmat,density,-4,wmat);  
+
+  // NOMEX
+
+  amat[0] = 12.011;
+  amat[1] = 1.;
+  amat[2] = 15.999;
+  amat[3] = 14.006;
+
+  zmat[0] = 6.;
+  zmat[1] = 1.;
+  zmat[2] = 8.;
+  zmat[3] = 7.;
+
+  wmat[0] = 14.;
+  wmat[1] = 22.;
+  wmat[2] = 2.;
+  wmat[3] = 2.;
+
+  density = 0.029;
+  AliMixture(15,"NOMEX",amat,zmat,density,-4,wmat);
+
+  // Makrolon C16H18O3
+
+  amat[0] = 12.011;
+  amat[1] = 1.;
+  amat[2] = 15.999;
+
+  zmat[0] = 6.;
+  zmat[1] = 1.;
+  zmat[2] = 8.;
+
+  wmat[0] = 16.;
+  wmat[1] = 18.;
+  wmat[2] = 3.;
   
-  arr->Delete(); // delete objects in this array
+  density = 1.2;
+
+  AliMixture(16,"Makrolon",amat,zmat,density,-3,wmat);
+
+  // Tedlar C2H3F
+
+  amat[0] = 12.011;
+  amat[1] = 1.;
+  amat[2] = 18.998;
+
+  zmat[0] = 6.;
+  zmat[1] = 1.;
+  zmat[2] = 9.;
+
+  wmat[0] = 2.;
+  wmat[1] = 3.; 
+  wmat[2] = 1.;
+
+  density = 1.71;
+
+  AliMixture(17, "Tedlar",amat,zmat,density,-3,wmat);  
   
-  delete arr; // deletes the TObjArray itselves
+  // Mylar C5H4O2
+
+  amat[0]=12.011;
+  amat[1]=1.;
+  amat[2]=15.9994;
+
+  zmat[0]=6.;
+  zmat[1]=1.;
+  zmat[2]=8.;
+
+  wmat[0]=5.;
+  wmat[1]=4.;
+  wmat[2]=2.; 
+
+  density = 1.39;
   
-}
+  AliMixture(18, "Mylar",amat,zmat,density,-3,wmat); 
+  // material for "prepregs"
+  // Epoxy - C14 H20 O3
+  // Quartz SiO2
+  // Carbon C
+  // prepreg1 60% C-fiber, 40% epoxy (vol)
+  amat[0]=12.011;
+  amat[1]=1.;
+  amat[2]=15.994;
 
-//_____________________________________________________________________________
-Int_t AliTPC::DistancetoPrimitive(Int_t , Int_t )
-{
-  //
-  // Calculate distance from TPC to mouse on the display
-  // Dummy procedure
-  //
-  return 9999;
-}
+  zmat[0]=6.;
+  zmat[1]=1.;
+  zmat[2]=8.;
 
-//_____________________________________________________________________________
-const int MAX_CLUSTER=nrow_low+nrow_up; 
-const int S_MAXSEC=24;
-const int L_MAXSEC=48;
-const int ROWS_TO_SKIP=21;
-const Float_t MAX_CHI2=15.;
-const Float_t THRESHOLD=8*zero_sup;
+  wmat[0]=0.923;
+  wmat[1]=0.023;
+  wmat[2]=0.054;
 
-//_____________________________________________________________________________
-static Double_t SigmaY2(Double_t r, Double_t tgl, Double_t pt)
-{
-  //
-  // Calculate spread in Y
-  //
-  pt=TMath::Abs(pt)*1000.;
-  Double_t x=r/pt;
-  tgl=TMath::Abs(tgl);
-  Double_t s=a_rphi - b_rphi*r*tgl + c_rphi*x*x + d_rphi*x;
-  if (s<0.4e-3) s=0.4e-3;
-  return s;
-}
+  density=1.859;
 
-//_____________________________________________________________________________
-static Double_t SigmaZ2(Double_t r, Double_t tgl) 
-{
+  AliMixture(19, "Prepreg1",amat,zmat,density,3,wmat);
+
+  //prepreg2 60% glass-fiber, 40% epoxy
+
+  amat[0]=12.01;
+  amat[1]=1.;
+  amat[2]=15.994;
+  amat[3]=28.086;
+
+  zmat[0]=6.;
+  zmat[1]=1.;
+  zmat[2]=8.;
+  zmat[3]=14.;
+
+  wmat[0]=0.194;
+  wmat[1]=0.023;
+  wmat[2]=0.443;
+  wmat[3]=0.34;
+
+  density=1.82;
+
+  AliMixture(20, "Prepreg2",amat,zmat,density,4,wmat);
+
+  //prepreg3 50% glass-fiber, 50% epoxy
+
+  amat[0]=12.01;
+  amat[1]=1.;
+  amat[2]=15.994;
+  amat[3]=28.086;
+
+  zmat[0]=6.;
+  zmat[1]=1.;
+  zmat[2]=8.;
+  zmat[3]=14.;
+
+  wmat[0]=0.257;
+  wmat[1]=0.03;
+  wmat[2]=0.412;
+  wmat[3]=0.3;
+
+  density=1.725;
+
+  AliMixture(21, "Prepreg3",amat,zmat,density,4,wmat);
+
+  // G10 60% SiO2 40% epoxy
+
+  amat[0]=12.01;
+  amat[1]=1.;
+  amat[2]=15.994;
+  amat[3]=28.086;
+
+  zmat[0]=6.;
+  zmat[1]=1.;
+  zmat[2]=8.;
+  zmat[3]=14.;
+
+  wmat[0]=0.194;
+  wmat[1]=0.023;
+  wmat[2]=0.443;
+  wmat[3]=0.340;
+
+  density=1.7;
+
+  AliMixture(22, "G10",amat,zmat,density,4,wmat);
+  // Al
+
+  amat[0] = 26.98;
+  zmat[0] = 13.;
+
+  density = 2.7;
+
+  AliMaterial(23,"Al",amat[0],zmat[0],density,999.,999.);
+
+  // Si (for electronics
+
+  amat[0] = 28.086;
+  zmat[0] = 14.;
+
+  density = 2.33;
+
+  AliMaterial(24,"Si",amat[0],zmat[0],density,999.,999.);
+
+  // Cu
+
+  amat[0] = 63.546;
+  zmat[0] = 29.;
+
+  density = 8.96;
+
+  AliMaterial(25,"Cu",amat[0],zmat[0],density,999.,999.);
+
+  // brass
+
+  amat[0] = 63.546;
+  zmat[0] = 29.;
   //
-  // Calculate spread in Z
+  amat[1]= 65.409;
+  zmat[1]= 30.;
   //
-  tgl=TMath::Abs(tgl);
-  Double_t s=a_z - b_z*r*tgl + c_z*tgl*tgl;
-  if (s<0.4e-3) s=0.4e-3;
-  return s;
-}
+  wmat[0]= 0.6;
+  wmat[1]= 0.4;
 
-//_____________________________________________________________________________
-inline Double_t f1(Double_t x1,Double_t y1,   //C
-                   Double_t x2,Double_t y2,
-                   Double_t x3,Double_t y3) 
-{
   //
-  // Function f1
+  density = 8.23;
+  
   //
-  Double_t d=(x2-x1)*(y3-y2)-(x3-x2)*(y2-y1);
-  Double_t a=0.5*((y3-y2)*(y2*y2-y1*y1+x2*x2-x1*x1)-
-                  (y2-y1)*(y3*y3-y2*y2+x3*x3-x2*x2));
-  Double_t b=0.5*((x2-x1)*(y3*y3-y2*y2+x3*x3-x2*x2)-
-                  (x3-x2)*(y2*y2-y1*y1+x2*x2-x1*x1));
-  Double_t xr=TMath::Abs(d/(d*x1-a)), yr=d/(d*y1-b);
+  AliMixture(33,"Brass",amat,zmat,density,2,wmat);
   
-  return -xr*yr/sqrt(xr*xr+yr*yr); 
-}
+  // Epoxy - C14 H20 O3
+  amat[0]=12.011;
+  amat[1]=1.;
+  amat[2]=15.9994;
 
+  zmat[0]=6.;
+  zmat[1]=1.;
+  zmat[2]=8.;
 
-//_____________________________________________________________________________
-inline Double_t f2(Double_t x1,Double_t y1,  //eta=C*x0
-                   Double_t x2,Double_t y2,
-                   Double_t x3,Double_t y3) 
-{
-  //
-  // Function f2
-  //
-  Double_t d=(x2-x1)*(y3-y2)-(x3-x2)*(y2-y1);
-  Double_t a=0.5*((y3-y2)*(y2*y2-y1*y1+x2*x2-x1*x1)-
-                  (y2-y1)*(y3*y3-y2*y2+x3*x3-x2*x2));
-  Double_t b=0.5*((x2-x1)*(y3*y3-y2*y2+x3*x3-x2*x2)-
-                  (x3-x2)*(y2*y2-y1*y1+x2*x2-x1*x1));
-  Double_t xr=TMath::Abs(d/(d*x1-a)), yr=d/(d*y1-b);
-  
-  return -a/(d*y1-b)*xr/sqrt(xr*xr+yr*yr);
-}
+  wmat[0]=14.;
+  wmat[1]=20.;
+  wmat[2]=3.;
 
-//_____________________________________________________________________________
-inline Double_t f3(Double_t x1,Double_t y1,  //tgl
-                   Double_t x2,Double_t y2,
-                   Double_t z1,Double_t z2) 
-{
+  density=1.25;
+
+  AliMixture(26,"Epoxy",amat,zmat,density,-3,wmat);
   //
-  // Function f3
+  // epoxy film - 90% epoxy, 10% glass fiber 
   //
-  return (z1 - z2)/sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2));
+  amat[0]=12.01;
+  amat[1]=1.;
+  amat[2]=15.994;
+  amat[3]=28.086;
+
+  zmat[0]=6.;
+  zmat[1]=1.;
+  zmat[2]=8.;
+  zmat[3]=14.;
+
+  wmat[0]=0.596;
+  wmat[1]=0.071;
+  wmat[2]=0.257;
+  wmat[3]=0.076;
+
+
+  density=1.345;
+
+  AliMixture(34, "Epoxy-film",amat,zmat,density,4,wmat);
+
+  // Plexiglas  C5H8O2
+
+  amat[0]=12.011;
+  amat[1]=1.;
+  amat[2]=15.9994;
+
+  zmat[0]=6.;
+  zmat[1]=1.;
+  zmat[2]=8.;
+
+  wmat[0]=5.;
+  wmat[1]=8.;
+  wmat[2]=2.;
+
+  density=1.18;
+
+  AliMixture(27,"Plexiglas",amat,zmat,density,-3,wmat);
+
+  // Carbon
+
+  amat[0]=12.011;
+  zmat[0]=6.;
+  density= 2.265;
+
+  AliMaterial(28,"C",amat[0],zmat[0],density,999.,999.);
+
+  // Fe (steel for the inner heat screen)
+  amat[0]=55.845;
+
+  zmat[0]=26.;
+
+  density=7.87;
+
+  AliMaterial(29,"Fe",amat[0],zmat[0],density,999.,999.);
+  //
+  // Peek - (C6H4-O-OC6H4-O-C6H4-CO)n
+  amat[0]=12.011;
+  amat[1]=1.;
+  amat[2]=15.9994;
+
+  zmat[0]=6.;
+  zmat[1]=1.;
+  zmat[2]=8.;
+
+  wmat[0]=19.;
+  wmat[1]=12.;
+  wmat[2]=3.;
+  //
+  density=1.3;
+  //
+  AliMixture(30,"Peek",amat,zmat,density,-3,wmat);  
+  //
+  //  Ceramics - Al2O3
+  //
+  amat[0] = 26.98;
+  amat[1]= 15.9994;
+
+  zmat[0] = 13.;
+  zmat[1]=8.;
+  wmat[0]=2.;
+  wmat[1]=3.;
+  density = 3.97;
+
+  AliMixture(31,"Alumina",amat,zmat,density,-2,wmat);   
+
+  //
+  // liquids
+  //
+
+  // water
+
+  amat[0]=1.;
+  amat[1]=15.9994;
+
+  zmat[0]=1.;
+  zmat[1]=8.;
+
+  wmat[0]=2.;
+  wmat[1]=1.;
+
+  density=1.;
+
+  AliMixture(32,"Water",amat,zmat,density,-2,wmat);  
+
+  //----------------------------------------------------------
+  // tracking media for gases
+  //----------------------------------------------------------
+
+  AliMedium(0, "Air", 11, 0, iSXFLD, sXMGMX, 10., 999., .1, .01, .1);
+  AliMedium(1, "Ne-CO2-N-1", 12, 0, iSXFLD, sXMGMX, 10., 999.,.1,.001, .001);
+  AliMedium(2, "Ne-CO2-N-2", 13, 1, iSXFLD, sXMGMX, 10., 999.,.1,.001, .001);
+  AliMedium(3,"CO2",10,0, iSXFLD, sXMGMX, 10., 999.,.1, .001, .001); 
+  AliMedium(20, "Ne-CO2-N-3", 30, 1, iSXFLD, sXMGMX, 10., 999.,.1,.001, .001);
+  //-----------------------------------------------------------  
+  // tracking media for solids
+  //-----------------------------------------------------------
+  
+  AliMedium(4,"Al",23,0, iSXFLD, sXMGMX, 10., 999., .1, .0005, .001);
+  AliMedium(5,"Kevlar",14,0, iSXFLD, sXMGMX, 10., 999., .1, .0005, .001);
+  AliMedium(6,"Nomex",15,0, iSXFLD, sXMGMX, 10., 999., .1, .001, .001);
+  AliMedium(7,"Makrolon",16,0, iSXFLD, sXMGMX, 10., 999., .1, .001, .001);
+  AliMedium(8,"Mylar",18,0, iSXFLD, sXMGMX, 10., 999., .1, .0005, .001);
+  AliMedium(9,"Tedlar",17,0, iSXFLD, sXMGMX, 10., 999., .1, .0005, .001);
+  //
+  AliMedium(10,"Prepreg1",19,0, iSXFLD, sXMGMX, 10., 999., .1, .0005, .001);
+  AliMedium(11,"Prepreg2",20,0, iSXFLD, sXMGMX, 10., 999., .1, .0005, .001);
+  AliMedium(12,"Prepreg3",21,0, iSXFLD, sXMGMX, 10., 999., .1, .0005, .001);
+  AliMedium(13,"Epoxy",26,0, iSXFLD, sXMGMX, 10., 999., .1, .0005, .001);
+
+  AliMedium(14,"Cu",25,0, iSXFLD, sXMGMX, 10., 999., .1, .001, .001);
+  AliMedium(15,"Si",24,0, iSXFLD, sXMGMX, 10., 999., .1, .001, .001);
+  AliMedium(16,"G10",22,0, iSXFLD, sXMGMX, 10., 999., .1, .001, .001);
+  AliMedium(17,"Plexiglas",27,0, iSXFLD, sXMGMX, 10., 999., .1, .001, .001);
+  AliMedium(18,"Steel",29,0, iSXFLD, sXMGMX, 10., 999., .1, .001, .001); 
+  AliMedium(19,"Peek",30,0, iSXFLD, sXMGMX, 10., 999., .1, .001, .001);
+  AliMedium(21,"Alumina",31,0, iSXFLD, sXMGMX, 10., 999., .1, .001, .001);    
+  AliMedium(22,"Water",32,0, iSXFLD, sXMGMX, 10., 999., .1, .001, .001);
+  AliMedium(23,"Brass",33,0, iSXFLD, sXMGMX, 10., 999., .1, .001, .001);
+  AliMedium(24,"Epoxyfm",34,0, iSXFLD, sXMGMX, 10., 999., .1, .0005, .001);  
 }
 
-//_____________________________________________________________________________
-static int FindProlongation(AliTPCtrack& t, const AliTPCSector *sec, 
-                           int s, int ri, int rf=0) 
+void AliTPC::GenerNoise(Int_t tablesize)
 {
   //
-  // Propagate track
+  //Generate table with noise
   //
-  int try_again=ROWS_TO_SKIP;
-  Double_t alpha=sec->GetAlpha();
-  int ns=int(2*TMath::Pi()/alpha)+1;
-  for (int nr=ri; nr>=rf; nr--) {
-    Double_t x=sec[s].GetX(nr), ymax=sec[s].GetMaxY(nr);
-    if (!t.PropagateTo(x)) break;
-    
-    const AliTPCcluster *cl=0;
-    Double_t max_chi2=MAX_CHI2;
-    const AliTPCRow& row=sec[s][nr];
-    Double_t sy2=SigmaY2(t.GetX(),t.GetTgl(),t.GetPt());
-    Double_t sz2=SigmaZ2(t.GetX(),t.GetTgl());
-    Double_t road=3.*sqrt(t.GetSigmaY2() + sy2), y=t.GetY(), z=t.GetZ();
-    
-    if (road>30) {
-      if (t>3) cerr<<t<<" AliTPCtrack warning: Too broad road !\n"; 
-      break;
-    }
+  if (fTPCParam==0) {
+    // error message
+    fNoiseDepth=0;
+    return;
+  }
+  if (fNoiseTable)  delete[] fNoiseTable;
+  fNoiseTable = new Float_t[tablesize];
+  fNoiseDepth = tablesize; 
+  fCurrentNoise =0; //!index of the noise in  the noise table 
+  
+  Float_t norm = fTPCParam->GetNoise()*fTPCParam->GetNoiseNormFac();
+  for (Int_t i=0;i<tablesize;i++) fNoiseTable[i]= gRandom->Gaus(0,norm);      
+}
+
+Float_t AliTPC::GetNoise()
+{
+  // get noise from table
+  //  if ((fCurrentNoise%10)==0) 
+  //  fCurrentNoise= gRandom->Rndm()*fNoiseDepth;
+  if (fCurrentNoise>=fNoiseDepth) fCurrentNoise=0;
+  return fNoiseTable[fCurrentNoise++];
+  //gRandom->Gaus(0, fTPCParam->GetNoise()*fTPCParam->GetNoiseNormFac()); 
+}
+
+
+Bool_t  AliTPC::IsSectorActive(Int_t sec) const
+{
+  //
+  // check if the sector is active
+  if (!fActiveSectors) return kTRUE;
+  else return fActiveSectors[sec]; 
+}
+
+void    AliTPC::SetActiveSectors(Int_t * sectors, Int_t n)
+{
+  // activate interesting sectors
+  SetTreeAddress();//just for security
+  if (!fActiveSectors) fActiveSectors = new Bool_t[fTPCParam->GetNSector()];
+  for (Int_t i=0;i<fTPCParam->GetNSector();i++) fActiveSectors[i]=kFALSE;
+  for (Int_t i=0;i<n;i++) 
+    if ((sectors[i]>=0) && sectors[i]<fTPCParam->GetNSector())  fActiveSectors[sectors[i]]=kTRUE;
     
-    if (row) 
-      for (int i=row.Find(y-road); i<row; i++) {
-       AliTPCcluster* c=(AliTPCcluster*)(row[i]);
-       if (c->fY > y+road) break;
-       if (c->IsUsed()) continue;
-       if ((c->fZ - z)*(c->fZ - z) > 9.*(t.GetSigmaZ2() + sz2)) continue;
-       Double_t chi2=t.GetPredictedChi2(c);
-       if (chi2 > max_chi2) continue;
-       max_chi2=chi2;
-       cl=c;       
-      }
-    if (cl) {
-      t.Update(cl,max_chi2);
-      try_again=ROWS_TO_SKIP;
-    } else {
-      if (try_again--) {
-       if (y > ymax) {
-         s = (s+1) % ns;
-         if (!t.Rotate(alpha)) break;
-       } else
-         if (y <-ymax) {
-           s = (s-1+ns) % ns;
-           if (!t.Rotate(-alpha)) break;
-         };
-       continue;
+}
+
+void    AliTPC::SetActiveSectors(Int_t flag)
+{
+  //
+  // activate sectors which were hitted by tracks 
+  //loop over tracks
+  SetTreeAddress();//just for security
+  if (fHitType==0) return;  // if Clones hit - not short volume ID information
+  if (!fActiveSectors) fActiveSectors = new Bool_t[fTPCParam->GetNSector()];
+  if (flag) {
+    for (Int_t i=0;i<fTPCParam->GetNSector();i++) fActiveSectors[i]=kTRUE;
+    return;
+  }
+  for (Int_t i=0;i<fTPCParam->GetNSector();i++) fActiveSectors[i]=kFALSE;
+  TBranch * branch=0;
+  if (fLoader->TreeH() == 0x0)
+   {
+     AliFatal("Can not find TreeH in folder");
+     return;
+   }
+  if (fHitType>1) branch = fLoader->TreeH()->GetBranch("TPC2");
+  else branch = fLoader->TreeH()->GetBranch("TPC");
+  Stat_t ntracks = fLoader->TreeH()->GetEntries();
+  // loop over all hits
+  AliDebug(1,Form("Got %d tracks", (Int_t) ntracks));
+  
+  for(Int_t track=0;track<ntracks;track++) {
+    ResetHits();
+    //
+    if (fTrackHits && fHitType&4) {
+      TBranch * br1 = fLoader->TreeH()->GetBranch("fVolumes");
+      TBranch * br2 = fLoader->TreeH()->GetBranch("fNVolumes");
+      br1->GetEvent(track);
+      br2->GetEvent(track);
+      Int_t *volumes = fTrackHits->GetVolumes();
+      for (Int_t j=0;j<fTrackHits->GetNVolumes(); j++) {
+       if (volumes[j]>-1 && volumes[j]<fTPCParam->GetNSector()) {
+         fActiveSectors[volumes[j]]=kTRUE;
+       }
+       else {
+           AliError(Form("Volume %d -> sector number %d is outside (0..%d)",
+                         j,
+                         volumes[j],
+                         fTPCParam->GetNSector()));
+       }
       }
-      break;
     }
+    
+    //
+//     if (fTrackHitsOld && fHitType&2) {
+//       TBranch * br = fLoader->TreeH()->GetBranch("fTrackHitsInfo");
+//       br->GetEvent(track);
+//       AliObjectArray * ar = fTrackHitsOld->fTrackHitsInfo;
+//       for (UInt_t j=0;j<ar->GetSize();j++){
+//     fActiveSectors[((AliTrackHitsInfo*)ar->At(j))->fVolumeID] =kTRUE;
+//       } 
+//     }    
   }
-  return s;
-}
+}  
+
+
+
 
 //_____________________________________________________________________________
-static void MakeSeeds(TObjArray& seeds,const AliTPCSector* sec,int i1,int i2)
+void AliTPC::Digits2Raw()
 {
+// convert digits of the current event to raw data
+
+  static const Int_t kThreshold = 0;
+
+  fLoader->LoadDigits();
+  TTree* digits = fLoader->TreeD();
+  if (!digits) {
+    AliError("No digits tree");
+    return;
+  }
+
   //
-  // Find seed for tracking
-  //
-  TMatrix C(5,5); TVector x(5);
-  int max_sec=L_MAXSEC/2;
-  for (int ns=0; ns<max_sec; ns++) {
-    int nl=sec[(ns-1+max_sec)%max_sec][i2];
-    int nm=sec[ns][i2];
-    int nu=sec[(ns+1)%max_sec][i2];
-    Double_t alpha=sec[ns].GetAlpha();
-    const AliTPCRow& r1=sec[ns][i1];
-    for (int is=0; is < r1; is++) {
-      Double_t x1=sec[ns].GetX(i1), y1=r1[is]->fY, z1=r1[is]->fZ;
-      for (int js=0; js < nl+nm+nu; js++) {
-       const AliTPCcluster *cl;
-       Double_t cs,sn;
-       //int ks;
-       
-       if (js<nl) {
-         //ks=(ns-1+max_sec)%max_sec;
-         const AliTPCRow& r2=sec[(ns-1+max_sec)%max_sec][i2];
-         cl=r2[js];
-         cs=cos(alpha); sn=sin(alpha);
-       } else 
-         if (js<nl+nm) {
-           //ks=ns;
-           const AliTPCRow& r2=sec[ns][i2];
-           cl=r2[js-nl];
-           cs=1; sn=0.;
-         } else {
-           //ks=(ns+1)%max_sec;
-           const AliTPCRow& r2=sec[(ns+1)%max_sec][i2];
-           cl=r2[js-nl-nm];
-           cs=cos(alpha); sn=-sin(alpha);
-         }
-       Double_t x2=sec[ns].GetX(i2), y2=cl->fY, z2=cl->fZ;
-       //if (z1*z2 < 0) continue;
-       //if (TMath::Abs(z1) < TMath::Abs(z2)) continue;
-       
-       Double_t tmp= x2*cs+y2*sn;
-       y2 =-x2*sn+y2*cs;
-       x2=tmp;     
-       
-       x(0)=y1;
-       x(1)=z1;
-       x(2)=f1(x1,y1,x2,y2,0.,0.);
-       x(3)=f2(x1,y1,x2,y2,0.,0.);
-       x(4)=f3(x1,y1,x2,y2,z1,z2);
-       
-       if (TMath::Abs(x(2)*x1-x(3)) >= 0.999) continue;
-       
-       if (TMath::Abs(x(4)) > 1.2) continue;
-       
-       Double_t a=asin(x(3));
-       /*
-         Double_t tgl1=z1*x(2)/(a+asin(x(2)*x1-x(3)));
-         Double_t tgl2=z2*x(2)/(a+asin(x(2)*x2-x(3)));
-         Double_t ratio=2*(tgl1-tgl2)/(tgl1+tgl2);
-         if (TMath::Abs(ratio)>0.0170) continue; //or > 0.005
-       */
-       Double_t zv=z1 - x(4)/x(2)*(a+asin(x(2)*x1-x(3)));
-       if (TMath::Abs(zv)>33.) continue; 
-       
-       
-       TMatrix X(6,6); X=0.; 
-       X(0,0)=r1[is]->fSigmaY2; X(1,1)=r1[is]->fSigmaZ2;
-       X(2,2)=cl->fSigmaY2;     X(3,3)=cl->fSigmaZ2;
-       X(4,4)=3./12.; X(5,5)=3./12.;
-       TMatrix F(5,6); F.UnitMatrix();
-       Double_t sy=sqrt(X(0,0)), sz=sqrt(X(1,1));
-       F(2,0)=(f1(x1,y1+sy,x2,y2,0.,0.)-x(2))/sy;
-       F(2,2)=(f1(x1,y1,x2,y2+sy,0.,0.)-x(2))/sy;
-       F(2,4)=(f1(x1,y1,x2,y2,0.,0.+sy)-x(2))/sy;
-       F(3,0)=(f2(x1,y1+sy,x2,y2,0.,0.)-x(3))/sy;
-       F(3,2)=(f2(x1,y1,x2,y2+sy,0.,0.)-x(3))/sy;
-       F(3,4)=(f2(x1,y1,x2,y2,0.,0.+sy)-x(3))/sy;
-       F(4,0)=(f3(x1,y1+sy,x2,y2,z1,z2)-x(4))/sy;
-       F(4,1)=(f3(x1,y1,x2,y2,z1+sz,z2)-x(4))/sz;
-       F(4,2)=(f3(x1,y1,x2,y2+sy,z1,z2)-x(4))/sy;
-       F(4,3)=(f3(x1,y1,x2,y2,z1,z2+sz)-x(4))/sz;
-       F(4,4)=0;
-       F(3,3)=0;
-       
-       TMatrix t(F,TMatrix::kMult,X);
-       C.Mult(t,TMatrix(TMatrix::kTransposed,F));
-       
-       TrackSeed *track=new TrackSeed(*(r1[is]),x,C);
-       FindProlongation(*track,sec,ns,i1-1,i2);
-       int ii=(i1-i2)/2;
-       if (*track >= ii) {seeds.AddLast(track); continue;}
-       else delete track;
+  AliSimDigits digarr;
+  AliSimDigits* digrow = &digarr;
+  digits->GetBranch("Segment")->SetAddress(&digrow);
+
+  const char* fileName = "AliTPCDDL.dat";
+  AliTPCBuffer* buffer  = new AliTPCBuffer(fileName);
+  //Verbose level
+  // 0: Silent
+  // 1: cout messages
+  // 2: txt files with digits 
+  //BE CAREFUL, verbose level 2 MUST be used only for debugging and
+  //it is highly suggested to use this mode only for debugging digits files
+  //reasonably small, because otherwise the size of the txt files can reach
+  //quickly several MB wasting time and disk space.
+  buffer->SetVerbose(0);
+
+  Int_t nEntries = Int_t(digits->GetEntries());
+  Int_t previousSector = -1;
+  Int_t subSector = 0;
+  for (Int_t i = 0; i < nEntries; i++) {
+    digits->GetEntry(i);
+    Int_t sector, row;
+    fTPCParam->AdjustSectorRow(digarr.GetID(), sector, row);
+    if(previousSector != sector) {
+      subSector = 0;
+      previousSector = sector;
+    }
+
+    if (sector < 36) { //inner sector [0;35]
+      if (row != 30) {
+       //the whole row is written into the output file
+       buffer->WriteRowBinary(kThreshold, digrow, 0, 0, 0, 
+                              sector, subSector, row);
+      } else {
+       //only the pads in the range [37;48] are written into the output file
+       buffer->WriteRowBinary(kThreshold, digrow, 37, 48, 1, 
+                              sector, subSector, row);
+       subSector = 1;
+       //only the pads outside the range [37;48] are written into the output file
+       buffer->WriteRowBinary(kThreshold, digrow, 37, 48, 2, 
+                              sector, subSector, row);
+      }//end else
+
+    } else { //outer sector [36;71]
+      if (row == 54) subSector = 2;
+      if ((row != 27) && (row != 76)) {
+       buffer->WriteRowBinary(kThreshold, digrow, 0, 0, 0,
+                              sector, subSector, row);
+      } else if (row == 27) {
+       //only the pads outside the range [43;46] are written into the output file
+       buffer->WriteRowBinary(kThreshold, digrow, 43, 46, 2,
+                                sector, subSector, row);
+       subSector = 1;
+       //only the pads in the range [43;46] are written into the output file
+       buffer->WriteRowBinary(kThreshold, digrow, 43, 46, 1,
+                                sector, subSector, row);
+      } else if (row == 76) {
+       //only the pads outside the range [33;88] are written into the output file
+       buffer->WriteRowBinary(kThreshold, digrow, 33, 88, 2,
+                              sector, subSector, row);
+       subSector = 3;
+       //only the pads in the range [33;88] are written into the output file
+       buffer->WriteRowBinary(kThreshold, digrow, 33, 88, 1,
+                                sector, subSector, row);
       }
+    }//end else
+  }//end for
+
+  delete buffer;
+  fLoader->UnloadDigits();
+
+  AliTPCDDLRawData rawWriter;
+  rawWriter.SetVerbose(0);
+
+  rawWriter.RawData(fileName);
+  gSystem->Unlink(fileName);
+
+}
+
+
+//_____________________________________________________________________________
+Bool_t AliTPC::Raw2SDigits(AliRawReader* rawReader){
+  // Converts the TPC raw data into summable digits
+  // The method is used for merging simulated and
+  // real data events
+  if (fLoader->TreeS() == 0x0 ) {
+    fLoader->MakeTree("S");
+  }
+
+  if(fDefaults == 0) SetDefaults();  // check if the parameters are set
+
+  //setup TPCDigitsArray 
+  if(GetDigitsArray()) delete GetDigitsArray();
+
+  AliTPCDigitsArray *arr = new AliTPCDigitsArray; 
+  arr->SetClass("AliSimDigits");
+  arr->Setup(fTPCParam);
+  arr->MakeTree(fLoader->TreeS());
+
+  SetDigitsArray(arr);
+
+  // set zero suppression to "0"
+  fTPCParam->SetZeroSup(0);
+
+  // Loop over sectors
+  const Int_t kmaxTime = fTPCParam->GetMaxTBin();
+  const Int_t kNIS = fTPCParam->GetNInnerSector();
+  const Int_t kNOS = fTPCParam->GetNOuterSector();
+  const Int_t kNS = kNIS + kNOS;
+
+  // Setup storage
+  AliTPCROC * roc = AliTPCROC::Instance();
+  Int_t nRowsMax = roc->GetNRows(roc->GetNSector()-1);
+  Int_t nPadsMax = roc->GetNPads(roc->GetNSector()-1,nRowsMax-1);
+  Short_t** allBins = new Short_t*[nRowsMax];
+  for (Int_t iRow = 0; iRow < nRowsMax; iRow++) {
+    Int_t maxBin = kmaxTime*nPadsMax;
+    allBins[iRow] = new Short_t[maxBin];
+    memset(allBins[iRow],0,sizeof(Short_t)*maxBin);
+  }
+
+  for(Int_t iSector = 0; iSector < kNS; iSector++) {
+    
+    Int_t nRows = fTPCParam->GetNRow(iSector);
+    Int_t nDDLs = 0, indexDDL = 0;
+    if (iSector < kNIS) {
+      nDDLs = 2;
+      indexDDL = iSector * 2;
+    }
+    else {
+      nDDLs = 4;
+      indexDDL = (iSector-kNIS) * 4 + kNIS * 2;
+    }
+
+    // Load the raw data for corresponding DDLs
+    rawReader->Reset();
+
+    AliTPCAltroMapping** mapping =AliTPCcalibDB::Instance()->GetMapping();
+    AliTPCRawStreamV3 input(rawReader,(AliAltroMapping**)mapping);
+    rawReader->Select("TPC",indexDDL,indexDDL+nDDLs-1);
+
+    // Clean storage
+    for (Int_t iRow = 0; iRow < nRowsMax; iRow++) {
+      Int_t maxBin = kmaxTime*nPadsMax;
+      memset(allBins[iRow],0,sizeof(Short_t)*maxBin);
+    }
+
+    // Begin loop over altro data
+    while (input.NextDDL()) {
+
+      if (input.GetSector() != iSector)
+       AliFatal(Form("Sector index mismatch ! Expected (%d), but got (%d) !",iSector,input.GetSector()));
+
+      //loop over pads
+      while ( input.NextChannel() ) {
+
+        Int_t iRow = input.GetRow();
+        if (iRow < 0 || iRow >= nRows)
+          AliFatal(Form("Pad-row index (%d) outside the range (%d -> %d) !",
+                        iRow, 0, nRows -1));
+        Int_t iPad = input.GetPad();
+
+        Int_t maxPad = fTPCParam->GetNPads(iSector,iRow);
+
+        if (iPad < 0 || iPad >= maxPad)
+          AliFatal(Form("Pad index (%d) outside the range (%d -> %d) !",
+                        iPad, 0, maxPad -1));
+
+        //loop over bunches
+        while ( input.NextBunch() ){
+          Int_t  startTbin    = (Int_t)input.GetStartTimeBin();
+          Int_t  bunchlength  = (Int_t)input.GetBunchLength();
+          const UShort_t *sig = input.GetSignals();
+          for (Int_t iTime = 0; iTime<bunchlength; iTime++){
+            Int_t iTimeBin=startTbin-iTime;
+            if ( iTimeBin < 0 || iTimeBin >= kmaxTime) {
+              continue;
+              //AliFatal(Form("Timebin index (%d) outside the range (%d -> %d) !",
+              //               iTimeBin, 0, kmaxTime -1));
+            }
+
+            Int_t maxBin = kmaxTime*maxPad;
+            if (((iPad*kmaxTime+iTimeBin) >= maxBin) ||
+                ((iPad*kmaxTime+iTimeBin) < 0))
+              AliFatal(Form("Index outside the allowed range"
+                            " Sector=%d Row=%d Pad=%d Timebin=%d"
+                            " (Max.index=%d)",iSector,iRow,iPad,iTimeBin,maxBin));
+            allBins[iRow][iPad*kmaxTime+iTimeBin] = sig[iTime];
+          }
+        }
+      } // End loop over altro data
+    }
+
+    // Now fill the digits array
+    if (fDigitsArray->GetTree()==0) {
+      AliFatal("Tree not set in fDigitsArray");
     }
+
+    for (Int_t iRow = 0; iRow < nRows; iRow++) {
+      AliDigits * dig = fDigitsArray->CreateRow(iSector,iRow);
+      Int_t maxPad = fTPCParam->GetNPads(iSector,iRow);
+      for(Int_t iPad = 0; iPad < maxPad; iPad++) {
+       for(Int_t iTimeBin = 0; iTimeBin < kmaxTime; iTimeBin++) {
+         Short_t q = allBins[iRow][iPad*kmaxTime + iTimeBin];
+         if (q <= 0) continue;
+         q *= 16;
+         dig->SetDigitFast((Short_t)q,iTimeBin,iPad);
+       }
+      }
+      fDigitsArray->StoreRow(iSector,iRow);
+      Int_t ndig = dig->GetDigitSize(); 
+       
+      AliDebug(10,
+              Form("*** Sector, row, compressed digits %d %d %d ***\n",
+                   iSector,iRow,ndig));        
+       
+      fDigitsArray->ClearRow(iSector,iRow);  
+
+    } // end of the sector digitization
+  }
+  // get LHC clock phase from the digits tree
+
+  TParameter<float> *ph; 
+  Float_t phase;
+  TTree *digtree = fLoader->TreeD();
+  //
+  if(digtree){ // if TreeD exists
+    ph = (TParameter<float>*)digtree->GetUserInfo()->FindObject("lhcphase0");
+    phase = ph->GetVal();
   }
+  else{ //TreeD does not exist
+    phase = 0.; 
+  }
+    //
+    // store lhc clock phase in S-digits tree
+    //
+    fLoader->TreeS()->GetUserInfo()->Add(new TParameter<float>("lhcphase0",phase));
+   //
+   fLoader->WriteSDigits("OVERWRITE");
+
+  if(GetDigitsArray()) delete GetDigitsArray();
+  SetDigitsArray(0x0);
+
+  // cleanup storage
+  for (Int_t iRow = 0; iRow < nRowsMax; iRow++)
+    delete [] allBins[iRow];
+  delete [] allBins;
+
+  return kTRUE;
 }
 
-//_____________________________________________________________________________
-void AliTPC::Clusters2Tracks()
+//______________________________________________________________________
+AliDigitizer* AliTPC::CreateDigitizer(AliRunDigitizer* manager) const
 {
-  //
-  // TPC Track finder from clusters.
-  //
-  if (!fClusters) return;
-  AliTPCSSector ssec[S_MAXSEC/2];
-  AliTPCLSector lsec[L_MAXSEC/2];
-  int ncl=fClusters->GetEntriesFast();
-  while (ncl--) {
-    AliTPCcluster *c=(AliTPCcluster*)fClusters->UncheckedAt(ncl);
-    int sec=int(c->fSector), row=int(c->fPadRow);
-    
-    if (sec<24) {
-      if (row<0 || row>nrow_low) {cerr<<"low !!!"<<row<<endl; continue;}
-      ssec[sec%12][row].InsertCluster(c);
-    } else {
-      if (row<0 || row>nrow_up ) {cerr<<"up  !!!"<<row<<endl; continue;}
-      sec -= 24;
-      lsec[sec%24][row].InsertCluster(c);
+  return new AliTPCDigitizer(manager);
+}
+//__
+void AliTPC::SDigits2Digits2(Int_t /*eventnumber*/)  
+{
+  //create digits from summable digits
+  GenerNoise(500000); //create teble with noise
+
+  //conect tree with sSDigits
+  TTree *t = fLoader->TreeS();
+
+  if (t == 0x0) {
+    fLoader->LoadSDigits("READ");
+    t = fLoader->TreeS();
+    if (t == 0x0) {
+      AliError("Can not get input TreeS");
+      return;
     }
   }
   
+  if (fLoader->TreeD() == 0x0) fLoader->MakeTree("D");
   
-  TObjArray seeds(20000);
-  MakeSeeds(seeds,lsec,nrow_up-1,nrow_up-1-8);
-  MakeSeeds(seeds,lsec,nrow_up-1-4,nrow_up-1-4-8);
-  
-  seeds.Sort();
+  AliSimDigits digarr, *dummy=&digarr;
+  TBranch* sdb = t->GetBranch("Segment");
+  if (sdb == 0x0) {
+    AliError("Can not find branch with segments in TreeS.");
+    return;
+  }  
+
+  sdb->SetAddress(&dummy);
+      
+  Stat_t nentries = t->GetEntries();
+
+  // set zero suppression
+
+  fTPCParam->SetZeroSup(2);
+
+  // get zero suppression
+
+  Int_t zerosup = fTPCParam->GetZeroSup();
+
+  //make tree with digits 
   
-  int found=0;
-  int nseed=seeds.GetEntriesFast();
+  AliTPCDigitsArray *arr = new AliTPCDigitsArray; 
+  arr->SetClass("AliSimDigits");
+  arr->Setup(fTPCParam);
+  arr->MakeTree(fLoader->TreeD());
   
-  for (int s=0; s<nseed; s++) {
-    AliTPCtrack& t=*((AliTPCtrack*)seeds.UncheckedAt(s));
-    Double_t alpha=t.GetAlpha();
-    if (alpha > 2.*TMath::Pi()) alpha -= 2.*TMath::Pi();  
-    if (alpha < 0.            ) alpha += 2.*TMath::Pi();  
-    int ns=int(alpha/lsec->GetAlpha() + 0.5);
-    
-    Double_t x=t.GetX();
-    int nr;
-    if (x<pad_row_up[nrow_up-1-4-7]) nr=nrow_up-1-4-8;
-    else if (x<pad_row_up[nrow_up-1-7]) nr=nrow_up-1-8;
-    else {cerr<<x<<" =x !!!\n"; continue;}
-    
-    int ls=FindProlongation(t,lsec,ns,nr-1);
-    
-    //   if (t < 25) continue;
-    
-    x=t.GetX(); alpha=lsec[ls].GetAlpha();          //
-    Double_t phi=ls*alpha + atan(t.GetY()/x);       // Find S-sector
-    int ss=int(0.5*(phi/alpha+1));                  //
-    alpha *= 2*(ss-0.5*ls);                         // and rotation angle
-    if (!t.Rotate(alpha)) continue;                 //
-    ss %= (S_MAXSEC/2);                             //
+  AliTPCParam * par = fTPCParam;
+
+  //Loop over segments of the TPC
+
+  for (Int_t n=0; n<nentries; n++) {
+    t->GetEvent(n);
+    Int_t sec, row;
+    if (!par->AdjustSectorRow(digarr.GetID(),sec,row)) {
+      AliWarning(Form("Invalid segment ID ! %d",digarr.GetID()));
+      continue;
+    }
+    if (!IsSectorActive(sec)) continue;
     
-    ss=FindProlongation(t,ssec,ss,nrow_low-1);
-    if (t < 30) continue;
+    AliSimDigits * digrow =(AliSimDigits*) arr->CreateRow(sec,row);
+    Int_t nrows = digrow->GetNRows();
+    Int_t ncols = digrow->GetNCols();
+
+    digrow->ExpandBuffer();
+    digarr.ExpandBuffer();
+    digrow->ExpandTrackBuffer();
+    digarr.ExpandTrackBuffer();
+
     
-    AddTrack(t);
-    t.UseClusters();
-    cerr<<found++<<'\r';
+    Short_t * pamp0 = digarr.GetDigits();
+    Int_t   * ptracks0 = digarr.GetTracks();
+    Short_t * pamp1 = digrow->GetDigits();
+    Int_t   * ptracks1 = digrow->GetTracks();
+    Int_t  nelems =nrows*ncols;
+    Int_t saturation = fTPCParam->GetADCSat() - 1;
+    //use internal structure of the AliDigits - for speed reason
+    //if you cahnge implementation
+    //of the Alidigits - it must be rewriten -
+    for (Int_t i= 0; i<nelems; i++){
+      Float_t q = TMath::Nint(Float_t(*pamp0)/16.+GetNoise());
+      if (q>zerosup){
+       if (q>saturation) q=saturation;      
+       *pamp1=(Short_t)q;
+
+       ptracks1[0]=ptracks0[0];        
+       ptracks1[nelems]=ptracks0[nelems];
+       ptracks1[2*nelems]=ptracks0[2*nelems];
+      }
+      pamp0++;
+      pamp1++;
+      ptracks0++;
+      ptracks1++;       
+    }
+
+    arr->StoreRow(sec,row);
+    arr->ClearRow(sec,row);   
   }  
+
+    
+  //write results
+  fLoader->WriteDigits("OVERWRITE");
+   
+  delete arr;
 }
+//__________________________________________________________________
+void AliTPC::SetDefaults(){
+  //
+  // setting the defaults
+  //
+   
+  // Set response functions
+
+  //
+  AliRunLoader* rl = (AliRunLoader*)fLoader->GetEventFolder()->FindObject(AliRunLoader::GetRunLoaderName());
+  rl->CdGAFile();
+  AliTPCParamSR *param=(AliTPCParamSR*)gDirectory->Get("75x40_100x60");
+  // if(param){
+//     AliInfo("You are using 2 pad-length geom hits with 3 pad-lenght geom digits...");
+//     delete param;
+//     param = new AliTPCParamSR();
+//   }
+//   else {
+//     param=(AliTPCParamSR*)gDirectory->Get("75x40_100x60_150x60");
+//   }
+  param = (AliTPCParamSR*)AliTPCcalibDB::Instance()->GetParameters();
+  if (!param->IsGeoRead()){
+      //
+      // read transformation matrices for gGeoManager
+      //
+      param->ReadGeoMatrices();
+    }
+  if(!param){
+    AliFatal("No TPC parameters found");
+  }
 
-//_____________________________________________________________________________
-void AliTPC::CreateMaterials()
-{
+
+  AliTPCPRF2D    * prfinner   = new AliTPCPRF2D;
+  AliTPCPRF2D    * prfouter1   = new AliTPCPRF2D;
+  AliTPCPRF2D    * prfouter2   = new AliTPCPRF2D;  
+
+  
+  //AliTPCRF1D     * rf    = new AliTPCRF1D(kTRUE);
+  //rf->SetGauss(param->GetZSigma(),param->GetZWidth(),1.);
+  //rf->SetOffset(3*param->GetZSigma());
+  //rf->Update();
   //
-  // Create Materials for for TPC
-  // Origin M.Kowalski
+  // Use gamma 4
   //
+  char  strgamma4[1000];
+  sprintf(strgamma4,"AliTPCRF1D::Gamma4((x-0.135+%f)*%f,55,160)",3*param->GetZSigma(), 1000000000*param->GetTSample()/param->GetZWidth());
   
-  AliMC* pMC = AliMC::GetMC();
+  TF1 * fgamma4 = new TF1("fgamma4",strgamma4, -1,1);
+  AliTPCRF1D     * rf    = new AliTPCRF1D(kTRUE,1000);
+  rf->SetParam(fgamma4,param->GetZWidth(), 1,0.2);
+  rf->SetOffset(3*param->GetZSigma()); 
+  rf->Update();
 
-  Int_t ISXFLD=gAlice->Field()->Integ();
-  Float_t SXMGMX=gAlice->Field()->Max();
-  
-  Float_t absl, radl, a, d, z;
-  Float_t dg;
-  Float_t x0ne;
-  Float_t buf[1];
-  Int_t nbuf;
-  
-  // --- Methane (CH4) --- 
-  Float_t am[2] = { 12.,1. };
-  Float_t zm[2] = { 6.,1. };
-  Float_t wm[2] = { 1.,4. };
-  Float_t dm    = 7.17e-4;
-  // --- The Neon CO2 90/10 mixture --- 
-  Float_t ag[2] = { 20.18 };
-  Float_t zg[2] = { 10. };
-  Float_t wg[2] = { .8,.2 };
-  Float_t dne   = 9e-4;        // --- Neon density in g/cm3 ---     
-  // --- Mylar (C5H4O2) --- 
-  Float_t amy[3] = { 12.,1.,16. };
-  Float_t zmy[3] = { 6.,1.,8. };
-  Float_t wmy[3] = { 5.,4.,2. };
-  Float_t dmy    = 1.39;
-  // --- CO2 --- 
-  Float_t ac[2] = { 12.,16. };
-  Float_t zc[2] = { 6.,8. };
-  Float_t wc[2] = { 1.,2. };
-  Float_t dc    = .001977;
-  // --- Carbon density and radiation length --- 
-  Float_t densc = 2.265;
-  Float_t radlc = 18.8;
-  // --- Silicon --- 
-  Float_t asi   = 28.09;
-  Float_t zsi   = 14.;
-  Float_t desi  = 2.33;
-  Float_t radsi = 9.36;
-  
-  // --- Define the various materials for GEANT --- 
-  AliMaterial(0, "Al $", 26.98, 13., 2.7, 8.9, 37.2);
-  x0ne = 28.94 / dne;
-  AliMaterial(1, "Ne $", 20.18, 10., dne, x0ne, 999.);
-  
-  // --  Methane, defined by the proportions of atoms 
-  
-  AliMixture(2, "Methane$", am, zm, dm, -2, wm);
+  TDirectory *savedir=gDirectory;
+  TFile *f=TFile::Open("$ALICE_ROOT/TPC/AliTPCprf2d.root");
+  if (!f->IsOpen()) 
+    AliFatal("Can't open $ALICE_ROOT/TPC/AliTPCprf2d.root !");
+
+  TString s;
+  prfinner->Read("prf_07504_Gati_056068_d02");
+  //PH Set different names
+  s=prfinner->GetGRF()->GetName();
+  s+="in";
+  prfinner->GetGRF()->SetName(s.Data());
+
+  prfouter1->Read("prf_10006_Gati_047051_d03");
+  s=prfouter1->GetGRF()->GetName();
+  s+="out1";
+  prfouter1->GetGRF()->SetName(s.Data());
+
+  prfouter2->Read("prf_15006_Gati_047051_d03");  
+  s=prfouter2->GetGRF()->GetName();
+  s+="out2";
+  prfouter2->GetGRF()->SetName(s.Data());
+
+  f->Close();
+  savedir->cd();
+
+  param->SetInnerPRF(prfinner);
+  param->SetOuter1PRF(prfouter1); 
+  param->SetOuter2PRF(prfouter2);
+  param->SetTimeRF(rf);
+
+  // set fTPCParam
+
+  SetParam(param);
+
+
+  fDefaults = 1;
+
+}
+//__________________________________________________________________  
+void AliTPC::Hits2Digits()  
+{
+  //
+  // creates digits from hits
+  //
+  if (!fTPCParam->IsGeoRead()){
+    //
+    // read transformation matrices for gGeoManager
+    //
+    fTPCParam->ReadGeoMatrices();
+  }
+
+  fLoader->LoadHits("read");
+  fLoader->LoadDigits("recreate");
+  AliRunLoader* runLoader = fLoader->GetRunLoader(); 
+
+  for (Int_t iEvent = 0; iEvent < runLoader->GetNumberOfEvents(); iEvent++) {
+    //PH    runLoader->GetEvent(iEvent);
+    Hits2Digits(iEvent);
+  }
+
+  fLoader->UnloadHits();
+  fLoader->UnloadDigits();
+} 
+//__________________________________________________________________  
+void AliTPC::Hits2Digits(Int_t eventnumber)  
+{ 
+ //----------------------------------------------------
+ // Loop over all sectors for a single event
+ //----------------------------------------------------
+  AliRunLoader* rl = (AliRunLoader*)fLoader->GetEventFolder()->FindObject(AliRunLoader::GetRunLoaderName());
+  rl->GetEvent(eventnumber);
+  SetActiveSectors();   
+  if (fLoader->TreeH() == 0x0) {
+    if(fLoader->LoadHits()) {
+      AliError("Can not load hits.");
+    }
+  }
+  SetTreeAddress();
   
-  // --- CO2, defined by the proportion of atoms 
+  if (fLoader->TreeD() == 0x0 ) {
+    fLoader->MakeTree("D");
+    if (fLoader->TreeD() == 0x0 ) {
+      AliError("Can not get TreeD");
+      return;
+    }
+  }
+
+  if(fDefaults == 0) SetDefaults();  // check if the parameters are set
+  GenerNoise(500000); //create teble with noise
+
+  //setup TPCDigitsArray 
+
+  if(GetDigitsArray()) delete GetDigitsArray();
+  
+  AliTPCDigitsArray *arr = new AliTPCDigitsArray; 
+  arr->SetClass("AliSimDigits");
+  arr->Setup(fTPCParam);
+
+  arr->MakeTree(fLoader->TreeD());
+  SetDigitsArray(arr);
+
+  fDigitsSwitch=0; // standard digits
+  // here LHC clock phase
+  Float_t lhcph = 0.;
+  switch (fLHCclockPhaseSw){
+  case 0: 
+    // no phase
+    lhcph=0.;
+    break;
+  case 1:
+    // random phase
+    lhcph = (Int_t)(gRandom->Rndm()/0.25);    
+    break;
+  case 2:
+    lhcph=0.;
+    // not implemented yet
+    break;
+  }
+  // adding phase to the TreeD user info 
+  fLoader->TreeD()->GetUserInfo()->Add(new TParameter<float>("lhcphase0",lhcph));
+  //
+  for(Int_t isec=0;isec<fTPCParam->GetNSector();isec++) 
+    if (IsSectorActive(isec)) {
+      AliDebug(1,Form("Hits2Digits: Sector %d is active.",isec));
+      Hits2DigitsSector(isec);
+    }
+    else {
+      AliDebug(1,Form("Hits2Digits: Sector %d is NOT active.",isec));
+    }
   
-  AliMixture(7, "CO2$", ac, zc, dc, -2, wc);
+  fLoader->WriteDigits("OVERWRITE"); 
   
-  // --  Get A,Z etc. for CO2 
+//this line prevents the crash in the similar one
+//on the beginning of this method
+//destructor attempts to reset the tree, which is deleted by the loader
+//need to be redesign
+  if(GetDigitsArray()) delete GetDigitsArray();
+  SetDigitsArray(0x0);
   
-  char namate[21];
-  pMC->Gfmate((*fIdmate)[7], namate, a, z, d, radl, absl, buf, nbuf);
+}
 
-  ag[1] = a;
-  zg[1] = z;
-  dg = dne * .9 + dc * .1;
+//__________________________________________________________________
+void AliTPC::Hits2SDigits2(Int_t eventnumber)  
+{ 
 
-  //-------------------------------------
-  
-  // --  Create Ne/CO2 90/10 mixture 
+  //-----------------------------------------------------------
+  //   summable digits - 16 bit "ADC", no noise, no saturation
+  //-----------------------------------------------------------
+
+  //----------------------------------------------------
+  // Loop over all sectors for a single event
+  //----------------------------------------------------
+
+  AliRunLoader* rl = fLoader->GetRunLoader();
+
+  rl->GetEvent(eventnumber);
+  if (fLoader->TreeH() == 0x0) {
+    if(fLoader->LoadHits()) {
+      AliError("Can not load hits.");
+      return;
+    }
+  }
+  SetTreeAddress();
+
+
+  if (fLoader->TreeS() == 0x0 ) {
+    fLoader->MakeTree("S");
+  }
   
-  AliMixture(3, "Gas-mixt $", ag, zg, dg, 2, wg);
-  AliMixture(4, "Gas-mixt $", ag, zg, dg, 2, wg);
+  if(fDefaults == 0) SetDefaults();
   
-  AliMaterial(5, "G10$", 20., 10., 1.7, 19.4, 999.);
-  AliMixture(6, "Mylar$", amy, zmy, dmy, -3, wmy);
+  GenerNoise(500000); //create table with noise
+  //setup TPCDigitsArray 
+
+  if(GetDigitsArray()) delete GetDigitsArray();
+
   
-  a = ac[0];
-  z = zc[0];
-  AliMaterial(8, "Carbon", a, z, densc, radlc, 999.);
+  AliTPCDigitsArray *arr = new AliTPCDigitsArray; 
+  arr->SetClass("AliSimDigits");
+  arr->Setup(fTPCParam);
+  arr->MakeTree(fLoader->TreeS());
+
+  SetDigitsArray(arr);
+
+  fDigitsSwitch=1; // summable digits
   
-  AliMaterial(9, "Silicon", asi, zsi, desi, radsi, 999.);
-  AliMaterial(99, "Air$", 14.61, 7.3, .001205, 30420., 67500.);
+    // set zero suppression to "0"
+  // here LHC clock phase
+  Float_t lhcph = 0.;
+  switch (fLHCclockPhaseSw){
+  case 0: 
+    // no phase
+    lhcph=0.;
+    break;
+  case 1:
+    // random phase
+    lhcph = (Int_t)(gRandom->Rndm()/0.25);    
+    break;
+  case 2:
+    lhcph=0.;
+    // not implemented yet
+    break;
+  }
+  // adding phase to the TreeS user info 
   
-  AliMedium(400, "Al wall$",  0, 0, ISXFLD, SXMGMX, 10., .1, .1, .1,   .1);
-  AliMedium(402, "Gas mix1$", 3, 0, ISXFLD, SXMGMX, 10., .01,.1, .001, .01);
-  AliMedium(403, "Gas mix2$", 3, 0, ISXFLD, SXMGMX, 10., .01,.1, .001, .01);
-  AliMedium(404, "Gas mix3$", 4, 1, ISXFLD, SXMGMX, 10., .01,.1, .001, .01);
-  AliMedium(405, "G10 pln$",  5, 0, ISXFLD, SXMGMX, 10., .1, .1, .1,   .1 );
-  AliMedium(406, "Mylar  $",  6, 0, ISXFLD, SXMGMX, 10., .01,.1, .001, .01);
-  AliMedium(407, "CO2    $",  7, 0, ISXFLD, SXMGMX, 10., .01,.1, .01,  .01);
-  AliMedium(408, "Carbon $",  8, 0, ISXFLD, SXMGMX, 10., .1, .1, .1,   .1 );
-  AliMedium(409, "Silicon$",  9, 0, ISXFLD, SXMGMX, 10., .1, .1, .1,   .1 );
-  AliMedium(499, "Air gap$", 99, 0, ISXFLD, SXMGMX, 10., .1, .1, .1,   .1 );
+  fLoader->TreeS()->GetUserInfo()->Add(new TParameter<float>("lhcphase0",lhcph));
+
+  fTPCParam->SetZeroSup(0);
+
+  for(Int_t isec=0;isec<fTPCParam->GetNSector();isec++) 
+    if (IsSectorActive(isec)) {
+      Hits2DigitsSector(isec);
+    }
+
+  fLoader->WriteSDigits("OVERWRITE");
+
+//this line prevents the crash in the similar one
+//on the beginning of this method
+//destructor attempts to reset the tree, which is deleted by the loader
+//need to be redesign
+  if(GetDigitsArray()) delete GetDigitsArray();
+  SetDigitsArray(0x0);
 }
+//__________________________________________________________________
 
-//_____________________________________________________________________________
-struct Bin {
-   const AliTPCdigit *dig;
-   int idx;
-   Bin() {dig=0; idx=-1;}
-};
-
-struct PreCluster : public AliTPCcluster {
-   const AliTPCdigit* summit;
-   int idx;
-   int cut;
-   int npeaks;
-   PreCluster() : AliTPCcluster() {cut=npeaks=0;}
-};
+void AliTPC::Hits2SDigits()  
+{ 
 
-//_____________________________________________________________________________
-static void FindCluster(int i, int j, Bin bins[][MAXTPCTBK+2], PreCluster &c) 
-{
-  //
-  // Find clusters
-  //
-  Bin& b=bins[i][j];
-  int q=b.dig->fSignal;
-  
-  if (q<0) { // digit is at the edge of the pad row
-    q=-q;
-    c.cut=1;
-  } 
-  if (b.idx >= 0 && b.idx != c.idx) {
-    c.idx=b.idx;
-    c.npeaks++;
+  //-----------------------------------------------------------
+  //   summable digits - 16 bit "ADC", no noise, no saturation
+  //-----------------------------------------------------------
+
+  if (!fTPCParam->IsGeoRead()){
+    //
+    // read transformation matrices for gGeoManager
+    //
+    fTPCParam->ReadGeoMatrices();
   }
   
-  if (q > TMath::Abs(c.summit->fSignal)) c.summit=b.dig;
-  
-  c.fY += i*q;
-  c.fZ += j*q;
-  c.fSigmaY2 += i*i*q;
-  c.fSigmaZ2 += j*j*q;
-  c.fQ += q;
-  
-  b.dig = 0;  b.idx = c.idx;
-  
-  if (bins[i-1][j].dig) FindCluster(i-1,j,bins,c);
-  if (bins[i][j-1].dig) FindCluster(i,j-1,bins,c);
-  if (bins[i+1][j].dig) FindCluster(i+1,j,bins,c);
-  if (bins[i][j+1].dig) FindCluster(i,j+1,bins,c);
+  fLoader->LoadHits("read");
+  fLoader->LoadSDigits("recreate");
+  AliRunLoader* runLoader = fLoader->GetRunLoader(); 
+
+  for (Int_t iEvent = 0; iEvent < runLoader->GetNumberOfEvents(); iEvent++) {
+    runLoader->GetEvent(iEvent);
+    SetTreeAddress();
+    SetActiveSectors();
+    Hits2SDigits2(iEvent);
+  }
   
+  fLoader->UnloadHits();
+  fLoader->UnloadSDigits();
+  if (fDebugStreamer) {
+    delete fDebugStreamer;
+    fDebugStreamer=0;
+  }    
 }
-
 //_____________________________________________________________________________
-void AliTPC::Digits2Clusters()
+
+void AliTPC::Hits2DigitsSector(Int_t isec)
 {
-  //
-  // simple TPC cluster finder from digits.
-  //
-  const Int_t MAX_PAD=200+2, MAX_BUCKET=MAXTPCTBK+2;
-  const Int_t Q_min=200;//75;
-  
-  TTree *t=gAlice->TreeD();
-  t->GetBranch("TPC")->SetAddress(&fDigits);
-  Int_t sectors_by_rows=(Int_t)t->GetEntries();
-  
-  int ncls=0;
-  
-  for (Int_t n=0; n<sectors_by_rows; n++) {
-    if (!t->GetEvent(n)) continue;
-    Bin bins[MAX_PAD][MAX_BUCKET];
-    AliTPCdigit *dig=(AliTPCdigit*)fDigits->UncheckedAt(0);
-    Int_t nsec=dig->fSector, nrow=dig->fPadRow;
-    Int_t ndigits=fDigits->GetEntriesFast();
-    
-    int npads;  int sign_z;
-    if (nsec<25) {
-      sign_z=(nsec<13) ? 1 : -1;
-      npads=npads_low[nrow-1];
-    } else {
-      sign_z=(nsec<49) ? 1 : -1;
-      npads=npads_up[nrow-1];
-    }
-    
-    int ndig;
-    for (ndig=0; ndig<ndigits; ndig++) {
-      dig=(AliTPCdigit*)fDigits->UncheckedAt(ndig);
-      int i=dig->fPad, j=dig->fTime;
-      if (dig->fSignal >= THRESHOLD) bins[i][j].dig=dig;
-      if (i==1 || i==npads || j==1 || j==MAXTPCTBK) dig->fSignal*=-1;
-    }
+  //-------------------------------------------------------------------
+  // TPC conversion from hits to digits.
+  //------------------------------------------------------------------- 
+
+  //-----------------------------------------------------------------
+  // Origin: Marek Kowalski  IFJ, Krakow, Marek.Kowalski@ifj.edu.pl
+  //-----------------------------------------------------------------
+
+  //-------------------------------------------------------
+  //  Get the access to the track hits
+  //-------------------------------------------------------
+
+  // check if the parameters are set - important if one calls this method
+  // directly, not from the Hits2Digits
+
+  if(fDefaults == 0) SetDefaults();
+
+  TTree *tH = fLoader->TreeH(); // pointer to the hits tree
+  if (tH == 0x0) {
+    AliFatal("Can not find TreeH in folder");
+    return;
+  }
+
+  Stat_t ntracks = tH->GetEntries();
+
+
+
+    TObjArray **row;
     
-    int ncl=0;
-    int i,j;
-    for (i=1; i<MAX_PAD-1; i++) {
-      for (j=1; j<MAX_BUCKET-1; j++) {
-       if (bins[i][j].dig == 0) continue;
-       PreCluster c; c.summit=bins[i][j].dig; c.idx=ncls;
-       FindCluster(i, j, bins, c);
-       //if (c.fQ <= Q_min) continue; //noise cluster
-       c.fY /= c.fQ;
-       c.fZ /= c.fQ;
-       c.fSigmaY2 = c.fSigmaY2/c.fQ - c.fY*c.fY + 1./12.;
-       c.fSigmaZ2 = c.fSigmaZ2/c.fQ - c.fZ*c.fZ + 1./12.;
-       c.fSigmaY2 *= pad_pitch_w*pad_pitch_w;
-       c.fSigmaZ2 *= z_end/MAXTPCTBK*z_end/MAXTPCTBK;
-       c.fSigmaY2 *= 0.022*8;
-       c.fSigmaZ2 *= 0.068*4;
-       c.fY = (c.fY - 0.5 - 0.5*npads)*pad_pitch_w;
-       c.fZ = z_end/MAXTPCTBK*c.fZ; 
-       c.fZ -= 3.*fwhm/2.35482*v_drift; // PASA delay 
-       c.fZ = sign_z*(z_end - c.fZ);
-       c.fSector=nsec-1;
-       c.fPadRow=nrow-1;
-       c.fTracks[0]=c.summit->fTracks[0];
-       c.fTracks[1]=c.summit->fTracks[1];
-       c.fTracks[2]=c.summit->fTracks[2];
-       
-       if (c.cut) {
-         c.fSigmaY2 *= 25.;
-         c.fSigmaZ2 *= 4.;
-       }
-       
-       AddCluster(c); ncls++; ncl++;
-      }
-    }
+    Int_t nrows =fTPCParam->GetNRow(isec);
+
+    row= new TObjArray* [nrows+2]; // 2 extra rows for cross talk
     
-    for (ndig=0; ndig<ndigits; ndig++) {
-      dig=(AliTPCdigit*)fDigits->UncheckedAt(ndig);
-      if (TMath::Abs(dig->fSignal) >= THRESHOLD/3) 
-       bins[dig->fPad][dig->fTime].dig=dig;
+    MakeSector(isec,nrows,tH,ntracks,row);
+
+    //--------------------------------------------------------
+    //   Digitize this sector, row by row
+    //   row[i] is the pointer to the TObjArray of TVectors,
+    //   each one containing electrons accepted on this
+    //   row, assigned into tracks
+    //--------------------------------------------------------
+
+    Int_t i;
+
+    if (fDigitsArray->GetTree()==0) {
+      AliFatal("Tree not set in fDigitsArray");
     }
-    
-    for (i=1; i<MAX_PAD-1; i++) {
-      for (j=1; j<MAX_BUCKET-1; j++) {
-       if (bins[i][j].dig == 0) continue;
-       PreCluster c; c.summit=bins[i][j].dig; c.idx=ncls;
-       FindCluster(i, j, bins, c);
-       if (c.fQ <= Q_min) continue; //noise cluster
-       if (c.npeaks>1) continue;    //overlapped cluster
-       c.fY /= c.fQ;
-       c.fZ /= c.fQ;
-       c.fSigmaY2 = c.fSigmaY2/c.fQ - c.fY*c.fY + 1./12.;
-       c.fSigmaZ2 = c.fSigmaZ2/c.fQ - c.fZ*c.fZ + 1./12.;
-       c.fSigmaY2 *= pad_pitch_w*pad_pitch_w;
-       c.fSigmaZ2 *= z_end/MAXTPCTBK*z_end/MAXTPCTBK;
-       c.fSigmaY2 *= 0.022*4;
-       c.fSigmaZ2 *= 0.068*4;
-       c.fY = (c.fY - 0.5 - 0.5*npads)*pad_pitch_w;
-       c.fZ = z_end/MAXTPCTBK*c.fZ; 
-       c.fZ -= 3.*fwhm/2.35482*v_drift; // PASA delay 
-       c.fZ = sign_z*(z_end - c.fZ);
-       c.fSector=nsec-1;
-       c.fPadRow=nrow-1;
-       c.fTracks[0]=c.summit->fTracks[0];
-       c.fTracks[1]=c.summit->fTracks[1];
-       c.fTracks[2]=c.summit->fTracks[2];
-       
-       if (c.cut) {
-         c.fSigmaY2 *= 25.;
-         c.fSigmaZ2 *= 4.;
-       }
+
+    for (i=0;i<nrows;i++){
+      
+      AliDigits * dig = fDigitsArray->CreateRow(isec,i); 
+
+      DigitizeRow(i,isec,row);
+
+      fDigitsArray->StoreRow(isec,i);
+
+      Int_t ndig = dig->GetDigitSize(); 
        
-       if (c.npeaks==0) {AddCluster(c); ncls++; ncl++;}
-       else {
-         new ((*fClusters)[c.idx]) AliTPCcluster(c);
-       }
-      }
+      AliDebug(10,
+              Form("*** Sector, row, compressed digits %d %d %d ***\n",
+                   isec,i,ndig));        
+       
+      fDigitsArray->ClearRow(isec,i);  
+
+   
+    } // end of the sector digitization
+
+    for(i=0;i<nrows+2;i++){
+      row[i]->Delete();  
+      delete row[i];   
     }
-    
-    cerr<<"sector, row, digits, clusters: "
-       <<nsec<<' '<<nrow<<' '<<ndigits<<' '<<ncl<<"                  \r";
-    
-    fDigits->Clear();
-    
-  }
-}
+      
+    delete [] row; // delete the array of pointers to TObjArray-s
+        
+
+} // end of Hits2DigitsSector
+
 
 //_____________________________________________________________________________
-void AliTPC::ElDiff(Float_t *xyz)
+void AliTPC::DigitizeRow(Int_t irow,Int_t isec,TObjArray **rows)
 {
-  //
-  // calculates the diffusion of a single electron
-  //
+  //-----------------------------------------------------------
+  // Single row digitization, coupling from the neighbouring
+  // rows taken into account
+  //-----------------------------------------------------------
+
+  //-----------------------------------------------------------------
+  // Origin: Marek Kowalski  IFJ, Krakow, Marek.Kowalski@ifj.edu.pl
+  // Modified: Marian Ivanov GSI Darmstadt, m.ivanov@gsi.de
+  //-----------------------------------------------------------------
+  Float_t zerosup = fTPCParam->GetZeroSup();
+  AliTPCCalPad * gainTPC = AliTPCcalibDB::Instance()->GetDedxGainFactor(); 
+  AliTPCCalPad * noiseTPC = AliTPCcalibDB::Instance()->GetPadNoise(); 
+  AliTPCCalROC * gainROC = gainTPC->GetCalROC(isec);  // pad gains per given sector
+  AliTPCCalROC * noiseROC = noiseTPC->GetCalROC(isec);  // noise per given sector
+
+
+  fCurrentIndex[1]= isec;
   
-  Float_t driftl;
+
+  Int_t nofPads = fTPCParam->GetNPads(isec,irow);
+  Int_t nofTbins = fTPCParam->GetMaxTBin();
+  Int_t indexRange[4];
   //
-  Float_t z0=xyz[2];
-  driftl=z_end-TMath::Abs(xyz[2]);
-  if(driftl<0.01) driftl=0.01;
-  driftl=TMath::Sqrt(driftl);
-  Float_t sig_t = driftl*diff_t;
-  Float_t sig_l = driftl*diff_l;
+  //  Integrated signal for this row
+  //  and a single track signal
+  //    
+
+  TMatrixF *m1 = new TMatrixF(0,nofPads,0,nofTbins); // integrated
+  TMatrixF *m2 = new TMatrixF(0,nofPads,0,nofTbins); // single
+  //
+  TMatrixF &total  = *m1;
+
+  //  Array of pointers to the label-signal list
+
+  Int_t nofDigits = nofPads*nofTbins; // number of digits for this row
+  Float_t  **pList = new Float_t* [nofDigits]; 
+
+  Int_t lp;
+  Int_t i1;   
+  for(lp=0;lp<nofDigits;lp++)pList[lp]=0; // set all pointers to NULL
   //
-  xyz[0]=gRandom->Gaus(xyz[0],sig_t);
-  xyz[1]=gRandom->Gaus(xyz[1],sig_t);
-  xyz[2]=gRandom->Gaus(xyz[2],sig_l);
+  //calculate signal 
   //
-  if (TMath::Abs(xyz[2])>z_end){
-    xyz[2]=z_end*TMath::Sign(1.,(double) z0);
+  Int_t row1=irow;
+  Int_t row2=irow+2; 
+  for (Int_t row= row1;row<=row2;row++){
+    Int_t nTracks= rows[row]->GetEntries();
+    for (i1=0;i1<nTracks;i1++){
+      fCurrentIndex[2]= row;
+      fCurrentIndex[3]=irow+1;
+      if (row==irow+1){
+       m2->Zero();  // clear single track signal matrix
+       Float_t trackLabel = GetSignal(rows[row],i1,m2,m1,indexRange); 
+       GetList(trackLabel,nofPads,m2,indexRange,pList);
+      }
+      else   GetSignal(rows[row],i1,0,m1,indexRange);
+    }
   }
-  if(xyz[2]*z0 < 0.){
-    xyz[2]=0.0001*TMath::Sign(1.,(double) z0);
-  } 
-}
+         
+  Int_t tracks[3];
+
+  AliDigits *dig = fDigitsArray->GetRow(isec,irow);
+  Int_t gi=-1;
+  Float_t fzerosup = zerosup+0.5;
+  for(Int_t it=0;it<nofTbins;it++){
+    for(Int_t ip=0;ip<nofPads;ip++){
+      gi++;
+      Float_t q=total(ip,it);      
+      if(fDigitsSwitch == 0){  
+       Float_t gain = gainROC->GetValue(irow,ip);  // get gain for given - pad-row pad 
+       Float_t noisePad = noiseROC->GetValue(irow,ip); 
+       //
+       q*=gain;
+       q+=GetNoise()*noisePad;
+        if(q <=fzerosup) continue; // do not fill zeros
+        q = TMath::Nint(q);
+        if(q >= fTPCParam->GetADCSat()) q = fTPCParam->GetADCSat() - 1;  // saturation
 
-//_____________________________________________________________________________
-void AliTPC::Hits2Clusters()
-{
+      }
+
+      else {
+       if(q <= 0.) continue; // do not fill zeros
+       if(q>2000.) q=2000.;
+       q *= 16.;
+       q = TMath::Nint(q);
+      }
+
+      //
+      //  "real" signal or electronic noise (list = -1)?
+      //    
+
+      for(Int_t j1=0;j1<3;j1++){
+       tracks[j1] = (pList[gi]) ?(Int_t)(*(pList[gi]+j1)) : -2;
+      }
+
+//Begin_Html
+/*
+  <A NAME="AliDigits"></A>
+  using of AliDigits object
+*/
+//End_Html
+      dig->SetDigitFast((Short_t)q,it,ip);
+      if (fDigitsArray->IsSimulated()) {
+       ((AliSimDigits*)dig)->SetTrackIDFast(tracks[0],it,ip,0);
+       ((AliSimDigits*)dig)->SetTrackIDFast(tracks[1],it,ip,1);
+       ((AliSimDigits*)dig)->SetTrackIDFast(tracks[2],it,ip,2);
+      }
+    
+    } // end of loop over time buckets
+  }  // end of lop over pads 
   //
-  // TPC simple cluster generator from hits
-  // obtained from the TPC Fast Simulator
+  // test
   //
-  Float_t sigma_rphi,sigma_z,cl_rphi,cl_z;
   //
-  GParticle *particle; // pointer to a given particle
-  AliTPChit *tpcHit; // pointer to a sigle TPC hit
-  TClonesArray *Particles; //pointer to the particle list
-  Int_t sector,nhits;
-  Int_t ipart;
-  Float_t xyz[5];
-  Float_t pl,pt,tanth,rpad,ratio;
-  Float_t rot_angle;
-  Float_t cph,sph;
+
+  // glitch filters if normal simulated digits
+  //
+  if(!fDigitsSwitch) ((AliSimDigits*)dig)->GlitchFilter();
+  //
+  //  This row has been digitized, delete nonused stuff
+  //
+
+  for(lp=0;lp<nofDigits;lp++){
+    if(pList[lp]) delete [] pList[lp];
+  }
   
+  delete [] pList;
+
+  delete m1;
+  delete m2;
+
+} // end of DigitizeRow
+
+//_____________________________________________________________________________
+
+Float_t AliTPC::GetSignal(TObjArray *p1, Int_t ntr, 
+             TMatrixF *m1, TMatrixF *m2,Int_t *indexRange)
+{
+
   //---------------------------------------------------------------
-  //  Get the access to the tracks 
+  //  Calculates 2-D signal (pad,time) for a single track,
+  //  returns a pointer to the signal matrix and the track label 
+  //  No digitization is performed at this level!!!
   //---------------------------------------------------------------
+
+  //-----------------------------------------------------------------
+  // Origin: Marek Kowalski  IFJ, Krakow, Marek.Kowalski@ifj.edu.pl
+  // Modified: Marian Ivanov 
+  //-----------------------------------------------------------------
+
+  TVector *tv;
+
+  tv = (TVector*)p1->At(ntr); // pointer to a track
+  TVector &v = *tv;
   
-  TTree *TH = gAlice->TreeH();
-  Stat_t ntracks = TH->GetEntries();
-  
-  //------------------------------------------------------------
-  // Loop over all sectors (72 sectors)
-  // Sectors 1-24 are lower sectors, 1-12 z>0, 13-24 z<0
-  // Sectors 25-72 are upper sectors, 25-48 z>0, 49-72 z<0
+  Float_t label = v(0);
+  Int_t centralPad = (fTPCParam->GetNPads(fCurrentIndex[1],fCurrentIndex[3]-1))/2;
+
+  Int_t nElectrons = (tv->GetNrows()-1)/5;
+  indexRange[0]=9999; // min pad
+  indexRange[1]=-1; // max pad
+  indexRange[2]=9999; //min time
+  indexRange[3]=-1; // max time
+
+  TMatrixF &signal = *m1;
+  TMatrixF &total = *m2;
   //
-  // First cluster for sector 1 starts at "0"
-  //------------------------------------------------------------
-  
-  
-  fClustersIndex[0] = 0;
-  
+  // Get LHC clock phase
   //
-  for(Int_t isec=1;isec<fNsectors+1;isec++){
-    //
-    if(isec < 25){
-      rot_angle = (isec < 13) ? (isec-1)*alpha_low : (isec-13)*alpha_low;
-    }
-    else {
-      rot_angle = (isec < 49) ? (isec-25)*alpha_up : (isec-49)*alpha_up;
-    }
-    
-    cph=TMath::Cos(rot_angle);
-    sph=TMath::Sin(rot_angle);
-    
-    //------------------------------------------------------------
-    // Loop over tracks
-    //------------------------------------------------------------
-    
-    for(Int_t track=0;track<ntracks;track++){
-      ResetHits();
-      TH->GetEvent(track);
-      //
-      //  Get number of the TPC hits and a pointer
-      //  to the particles
-      //
-      nhits=fHits->GetEntriesFast();
-      Particles=gAlice->Particles();
-      //
-      // Loop over hits
-      //
-      for(Int_t hit=0;hit<nhits;hit++){
-       tpcHit=(AliTPChit*)fHits->UncheckedAt(hit);
-       sector=tpcHit->fSector; // sector number
-       if(sector != isec) continue; //terminate iteration
-       ipart=tpcHit->fTrack;
-       particle=(GParticle*)Particles->UncheckedAt(ipart);
-       pl=particle->GetPz();
-       pt=particle->GetPT();
-       if(pt < 1.e-9) pt=1.e-9;
-       tanth=pl/pt;
-       tanth = TMath::Abs(tanth);
-       rpad=TMath::Sqrt(tpcHit->fX*tpcHit->fX + tpcHit->fY*tpcHit->fY);
-       ratio=0.001*rpad/pt; // pt must be in MeV/c - historical reason
-       
-       //   space-point resolutions
-       
-       sigma_rphi=SigmaY2(rpad,tanth,pt);
-       sigma_z   =SigmaZ2(rpad,tanth   );
-       
-       //   cluster widths
-       
-       cl_rphi=ac_rphi-bc_rphi*rpad*tanth+cc_rphi*ratio*ratio;
-       cl_z=ac_z-bc_z*rpad*tanth+cc_z*tanth*tanth;
-       
-       // temporary protection
+  TParameter<float> *ph;
+  if(fDigitsSwitch){// s-digits
+    ph = (TParameter<float>*)fLoader->TreeS()->GetUserInfo()->FindObject("lhcphase0");  
+  }
+  else{ // normal digits
+    ph = (TParameter<float>*)fLoader->TreeD()->GetUserInfo()->FindObject("lhcphase0");
+  } 
+  //  Loop over all electrons
+  //
+  for(Int_t nel=0; nel<nElectrons; nel++){
+    Int_t idx=nel*5;
+    Float_t aval =  v(idx+4);
+    Float_t eltoadcfac=aval*fTPCParam->GetTotalNormFac(); 
+    Float_t xyz[4]={v(idx+1),v(idx+2),v(idx+3),v(idx+5)};
+    Int_t n = ((AliTPCParamSR*)fTPCParam)->CalcResponseFast(xyz,fCurrentIndex,
+                                                           fCurrentIndex[3],ph->GetVal());
+
+    Int_t *index = fTPCParam->GetResBin(0);  
+    Float_t *weight = & (fTPCParam->GetResWeight(0));
+
+    if (n>0) for (Int_t i =0; i<n; i++){       
+      Int_t pad=index[1]+centralPad;  //in digit coordinates central pad has coordinate 0
+
+      if (pad>=0){
+       Int_t time=index[2];     
+       Float_t qweight = *(weight)*eltoadcfac;
        
-       if(sigma_rphi < 0.) sigma_rphi=0.4e-3;
-       if(sigma_z < 0.) sigma_z=0.4e-3;
-       if(cl_rphi < 0.) cl_rphi=2.5e-3;
-       if(cl_z < 0.) cl_z=2.5e-5;
+       if (m1!=0) signal(pad,time)+=qweight;
+       total(pad,time)+=qweight;
+       if (indexRange[0]>pad) indexRange[0]=pad;
+       if (indexRange[1]<pad) indexRange[1]=pad;
+       if (indexRange[2]>time) indexRange[2]=time;
+       if (indexRange[3]<time) indexRange[3]=time;
        
+       index+=3;
+       weight++;       
+
+      }         
+    }
+  } // end of loop over electrons
+  
+  return label; // returns track label when finished
+}
+
+//_____________________________________________________________________________
+void AliTPC::GetList(Float_t label,Int_t np,TMatrixF *m,
+                     Int_t *indexRange, Float_t **pList)
+{
+  //----------------------------------------------------------------------
+  //  Updates the list of tracks contributing to digits for a given row
+  //----------------------------------------------------------------------
+
+  //-----------------------------------------------------------------
+  // Origin: Marek Kowalski  IFJ, Krakow, Marek.Kowalski@ifj.edu.pl
+  //-----------------------------------------------------------------
+
+  TMatrixF &signal = *m;
+
+  // lop over nonzero digits
+
+  for(Int_t it=indexRange[2];it<indexRange[3]+1;it++){
+    for(Int_t ip=indexRange[0];ip<indexRange[1]+1;ip++){
+
+
+      // accept only the contribution larger than 500 electrons (1/2 s_noise)
+
+      if(signal(ip,it)<0.5) continue; 
+
+      Int_t globalIndex = it*np+ip; // globalIndex starts from 0!
+        
+      if(!pList[globalIndex]){
+        
+       // 
+       // Create new list (6 elements - 3 signals and 3 labels),
        //
+
+       pList[globalIndex] = new Float_t [6];
+
+       // set list to -1 
+       
+       *pList[globalIndex] = -1.;
+       *(pList[globalIndex]+1) = -1.;
+       *(pList[globalIndex]+2) = -1.;
+       *(pList[globalIndex]+3) = -1.;
+       *(pList[globalIndex]+4) = -1.;
+       *(pList[globalIndex]+5) = -1.;
+
+       *pList[globalIndex] = label;
+       *(pList[globalIndex]+3) = signal(ip,it);
+      }
+      else {
+
+       // check the signal magnitude
+
+       Float_t highest = *(pList[globalIndex]+3);
+       Float_t middle = *(pList[globalIndex]+4);
+       Float_t lowest = *(pList[globalIndex]+5);
        
        //
-       // smearing --> rotate to the 1 (13) or to the 25 (49) sector,
-       // then the inaccuracy in a X-Y plane is only along Y (pad row)!
+       //  compare the new signal with already existing list
        //
-       Float_t xprim= tpcHit->fX*cph + tpcHit->fY*sph;
-       Float_t yprim=-tpcHit->fX*sph + tpcHit->fY*cph;
-       xyz[0]=gRandom->Gaus(yprim,TMath::Sqrt(sigma_rphi));   // y
-       xyz[1]=gRandom->Gaus(tpcHit->fZ,TMath::Sqrt(sigma_z)); // z 
-       xyz[2]=tpcHit->fQ;                                     // q
-       xyz[3]=sigma_rphi;                                     // fSigmaY2
-       xyz[4]=sigma_z;                                        // fSigmaZ2
        
-       //find row number
-       int row;
-       if (xprim > 0.5*(pad_row_up[0]+pad_row_low[nrow_low-1])) {
-          for (row=0; row<nrow_up; row++) if (xprim < pad_row_up[row]) break;
-       } else {
-          for (row=0; row<nrow_low; row++) if (xprim < pad_row_low[row]) break;
+       if(signal(ip,it)<lowest) continue; // neglect this track
+
+       //
+
+       if (signal(ip,it)>highest){
+         *(pList[globalIndex]+5) = middle;
+         *(pList[globalIndex]+4) = highest;
+         *(pList[globalIndex]+3) = signal(ip,it);
+         
+         *(pList[globalIndex]+2) = *(pList[globalIndex]+1);
+         *(pList[globalIndex]+1) = *pList[globalIndex];
+         *pList[globalIndex] = label;
        }
-       
-       // and finally add the cluster
-       Int_t tracks[5]={tpcHit->fTrack+1, 0, 0, sector-1, row-1};
-       AddCluster(xyz,tracks);
-       
-      } // end of loop over hits
-    }   // end of loop over tracks 
-    
-    fClustersIndex[isec] = fNclusters; // update clusters index
-    
-  } // end of loop over sectors
-  
-  fClustersIndex[fNsectors]--; // set end of the clusters buffer
-  
-}
+       else if (signal(ip,it)>middle){
+         *(pList[globalIndex]+5) = middle;
+         *(pList[globalIndex]+4) = signal(ip,it);
+         
+         *(pList[globalIndex]+2) = *(pList[globalIndex]+1);
+         *(pList[globalIndex]+1) = label;
+       }
+       else{
+         *(pList[globalIndex]+5) = signal(ip,it);
+         *(pList[globalIndex]+2) = label;
+       }
+      }
+      
+    } // end of loop over pads
+  } // end of loop over time bins
 
-//_____________________________________________________________________________
-void AliTPC::Hits2Digits()
+}//end of GetList
+//___________________________________________________________________
+void AliTPC::MakeSector(Int_t isec,Int_t nrows,TTree *TH,
+                        Stat_t ntracks,TObjArray **row)
 {
-  //
-  // TPC conversion from hits to digits.
-  //
-  
-  Int_t i;
-  //
-  AliTPChit *tpcHit; // pointer to a sigle TPC hit
-  //
-  Float_t xyz[3];
-  Float_t rot_angle;
-  //-------------------------------------------------------
-  //  Get the access to the tracks 
-  //-------------------------------------------------------
-  TTree *TH = gAlice->TreeH();
-  Stat_t ntracks = TH->GetEntries();
-  
-  //----------------------------------------------------
-  // Loop over all sectors (72 sectors)
-  // Sectors 1-24 are lower sectors, 1-12 z>0, 13-24 z<0
-  // Sectors 25-72 are upper sectors, 25-48 z>0, 49-72 z<0
-  //----------------------------------------------------
-  
-  for(Int_t isec=1;isec<fNsectors+1;isec++){ 
-    
-    //
-    printf("*** Processing sector number %d ***\n",isec);
-    
-    if(isec < 25){
-      rot_angle = (isec < 13) ? (isec-1)*alpha_low : (isec-13)*alpha_low;
-    }
-    else {
-      rot_angle = (isec < 49) ? (isec-25)*alpha_up : (isec-49)*alpha_up;
+
+  //-----------------------------------------------------------------
+  // Prepares the sector digitization, creates the vectors of
+  // tracks for each row of this sector. The track vector
+  // contains the track label and the position of electrons.
+  //-----------------------------------------------------------------
+
+  // 
+  // The trasport of the electrons through TPC drift volume
+  //    Drift (drift velocity + velocity map(not yet implemented)))
+  //    Application of the random processes (diffusion, gas gain)
+  //    Systematic effects (ExB effect in drift volume + ROCs)  
+  //
+  // Algorithm:
+  // Loop over primary electrons:
+  //    Creation of the secondary electrons
+  //    Loop over electrons (primary+ secondaries)
+  //        Global coordinate frame:
+  //          1. Skip electrons if attached  
+  //          2. ExB effect in drift volume
+  //             a.) Simulation   calib->GetExB()->CorrectInverse(dxyz0,dxyz1);
+  //             b.) Reconstruction -  calib->GetExB()->CorrectInverse(dxyz0,dxyz1);
+  //          3. Generation of gas gain (Random - Exponential distribution) 
+  //          4. TransportElectron function (diffusion)
+  //
+  //        5. Conversion to the local coordinate frame  pad-row, pad, timebin
+  //        6. Apply Time0 shift - AliTPCCalPad class 
+  //            a.) Plus sign in simulation
+  //            b.) Minus sign in reconstruction 
+  // end of loop          
+  //
+  //-----------------------------------------------------------------
+  // Origin: Marek Kowalski  IFJ, Krakow, Marek.Kowalski@ifj.edu.pl
+  // Origin: Marian Ivanov,  marian.ivanov@cern.ch
+  //-----------------------------------------------------------------
+  AliTPCcalibDB* const calib=AliTPCcalibDB::Instance();
+  if (gAlice){ // Set correctly the magnetic field in the ExB calculation
+    if (!calib->GetExB()){
+      AliMagF * field = ((AliMagF*)TGeoGlobalMagField::Instance()->GetField()); 
+      if (field) {
+       calib->SetExBField(field);
+      }
     }
+  }
+
+  Float_t gasgain = fTPCParam->GetGasGain();
+  gasgain = gasgain/fGainFactor;
+  Int_t i;
+  Float_t xyz[5]; 
+
+  AliTPChit *tpcHit; // pointer to a sigle TPC hit    
+  //MI change
+  TBranch * branch=0;
+  if (fHitType>1) branch = TH->GetBranch("TPC2");
+  else branch = TH->GetBranch("TPC");
+
+  //----------------------------------------------
+  // Create TObjArray-s, one for each row,
+  // each TObjArray will store the TVectors
+  // of electrons, one TVectors per each track.
+  //---------------------------------------------- 
     
-    Int_t nrows = (isec<25) ? 23 : 52;
-    
-    
-    Float_t cph=TMath::Cos(rot_angle);
-    Float_t sph=TMath::Sin(rot_angle);
-    
-    
-    
-    //----------------------------------------------
-    // Create TObjArray-s, one for each row
-    //---------------------------------------------- 
-    
-    TObjArray **row = new TObjArray* [nrows];
-    for(i=0; i<nrows; i++){
-      row[i] = new TObjArray;
-    }
+  Int_t *nofElectrons = new Int_t [nrows+2]; // electron counter for each row
+  TVector **tracks = new TVector* [nrows+2]; //pointers to the track vectors
+
+  for(i=0; i<nrows+2; i++){
+    row[i] = new TObjArray;
+    nofElectrons[i]=0;
+    tracks[i]=0;
+  }
+
+
+  //--------------------------------------------------------------------
+  //  Loop over tracks, the "track" contains the full history
+  //--------------------------------------------------------------------
+  
+  Int_t previousTrack,currentTrack;
+  previousTrack = -1; // nothing to store so far!
+
+  for(Int_t track=0;track<ntracks;track++){
+    Bool_t isInSector=kTRUE;
+    ResetHits();
+    isInSector = TrackInVolume(isec,track);
+    if (!isInSector) continue;
+    //MI change
+    branch->GetEntry(track); // get next track
     
-    //----------------------------------------------
-    // Loop over tracks
-    //----------------------------------------------
-    for(Int_t track=0;track<ntracks;track++){  
-      ResetHits();
-      TH->GetEvent(track); 
+    //M.I. changes
+
+    tpcHit = (AliTPChit*)FirstHit(-1);
+
+    //--------------------------------------------------------------
+    //  Loop over hits
+    //--------------------------------------------------------------
+
+
+    while(tpcHit){
       
-      //------------------------------------------------
-      //  Get number of the TPC hits and a pointer
-      //  to the particles
-      //------------------------------------------------
-      Int_t nhits=fHits->GetEntriesFast();
-      if(nhits == 0) continue; 
+      Int_t sector=tpcHit->fSector; // sector number
+      if(sector != isec){
+       tpcHit = (AliTPChit*) NextHit();
+       continue; 
+      }
+
+      // Remove hits which arrive before the TPC opening gate signal
+      if(((fTPCParam->GetZLength(isec)-TMath::Abs(tpcHit->Z()))
+         /fTPCParam->GetDriftV()+tpcHit->Time())<fTPCParam->GetGateDelay()) {
+       tpcHit = (AliTPChit*) NextHit();
+       continue;
+      }
+
+      currentTrack = tpcHit->Track(); // track number
+
+      if(currentTrack != previousTrack){
+                          
+       // store already filled fTrack
+              
+       for(i=0;i<nrows+2;i++){
+         if(previousTrack != -1){
+           if(nofElectrons[i]>0){
+             TVector &v = *tracks[i];
+             v(0) = previousTrack;
+             tracks[i]->ResizeTo(5*nofElectrons[i]+1); // shrink if necessary
+             row[i]->Add(tracks[i]);                     
+           }
+           else {
+             delete tracks[i]; // delete empty TVector
+             tracks[i]=0;
+           }
+         }
+
+         nofElectrons[i]=0;
+         tracks[i] = new TVector(601); // TVectors for the next fTrack
+
+       } // end of loop over rows
+              
+       previousTrack=currentTrack; // update track label 
+      }
+          
+      Int_t qI = (Int_t) (tpcHit->fQ); // energy loss (number of electrons)
+
+      //---------------------------------------------------
+      //  Calculate the electron attachment probability
+      //---------------------------------------------------
+
+
+      Float_t time = 1.e6*(fTPCParam->GetZLength(isec)-TMath::Abs(tpcHit->Z()))
+       /fTPCParam->GetDriftV(); 
+      // in microseconds!      
+      Float_t attProb = fTPCParam->GetAttCoef()*
+       fTPCParam->GetOxyCont()*time; //  fraction! 
+   
       //-----------------------------------------------
-      //  Create vectors for storing the track information,
-      //  one vector per track per row,
-      //  first element is a track number and then
-      //  there are (y,z) pairs * number of electrons
-      //----------------------------------------------
-      
-      TVector **tr = new TVector* [nrows];
-      Int_t *n_of_electrons= new int [nrows]; // electron counter 
-      for(i=0;i<nrows;i++){
-       tr[i] = new TVector(241); // 120 electrons initialy
-       n_of_electrons[i]=0;
-      } 
-      //-----------------------------------------------------
-      // Loop over hits
-      //------------------------------------------------------
-      for(Int_t hit=0;hit<nhits;hit++){
-       tpcHit=(AliTPChit*)fHits->UncheckedAt(hit);
-       Int_t sector=tpcHit->fSector; // sector number
-       if(sector != isec) continue; //terminate iteration
-       
-       xyz[0]=tpcHit->fX;
-       xyz[1]=tpcHit->fY;
-       xyz[2]=tpcHit->fZ;
-       Int_t QI = (Int_t) (tpcHit->fQ); // energy loss (number of electrons)
-       
-       //-----------------------------------------------
-       //  Rotate the electron cluster to sector 1,13,25,49
-       //-----------------------------------------------
-       Float_t xprim=xyz[0]*cph+xyz[1]*sph;
-       Float_t yprim=-xyz[0]*sph+xyz[1]*cph;
-       Float_t zprim=xyz[2]; 
+      //  Loop over electrons
+      //-----------------------------------------------
+      Int_t index[3];
+      index[1]=isec;
+      for(Int_t nel=0;nel<qI;nel++){
+       // skip if electron lost due to the attachment
+       if((gRandom->Rndm(0)) < attProb) continue; // electron lost!
        
-       //-------------------------------------
-       // Loop over electrons
-       //-------------------------------------
-       for(Int_t nel=0;nel<QI;nel++){
-         xyz[0]=xprim;  //
-         xyz[1]=yprim;  // Keep the initial cluster position!
-         xyz[2]=zprim;  //
-         
-         ElDiff(xyz); // Appply the diffusion
-         
-         Float_t row_first; 
-         Int_t row_number;
-         row_first = (isec<25) ? pad_row_low[0] : pad_row_up[0];
-         
-         row_number=(Int_t) ((xyz[0]-row_first+0.5*pad_pitch_l)/pad_pitch_l);
-         
-         // Check if out of range
-         
-          if((xyz[0]-row_first+0.5*pad_pitch_l) < 0 
-            || row_number > (nrows-1)) continue;
-          
-         n_of_electrons[row_number]++;
+       //
+       // ExB effect
+       //
+       Double_t dxyz0[3],dxyz1[3];
+       dxyz0[0]=tpcHit->X();
+       dxyz0[1]=tpcHit->Y();
+       dxyz0[2]=tpcHit->Z();   
+       if (calib->GetExB()){
+         calib->GetExB()->CorrectInverse(dxyz0,dxyz1);
+       }else{
+         AliError("Not valid ExB calibration");
+         dxyz1[0]=tpcHit->X();
+         dxyz1[1]=tpcHit->Y();
+         dxyz1[2]=tpcHit->Z();         
+       }
+       xyz[0]=dxyz1[0];
+       xyz[1]=dxyz1[1];
+       xyz[2]=dxyz1[2];        
+       //
+       //
+       //
+       // protection for the nonphysical avalanche size (10**6 maximum)
+       //  
+       Double_t rn=TMath::Max(gRandom->Rndm(0),1.93e-22);
+       xyz[3]= (Float_t) (-gasgain*TMath::Log(rn)); 
+       index[0]=1;
          
-         //
-         // Expand vector if necessary
-         //
-         if(n_of_electrons[row_number]>120){
-           Int_t range = tr[row_number]->GetNrows();
-           if(n_of_electrons[row_number] > (range-1)/2){
-             tr[row_number]->ResizeTo(range+30); // Add 15 electrons
-           }
+       TransportElectron(xyz,index);    
+       Int_t rowNumber;
+       Int_t padrow = fTPCParam->GetPadRow(xyz,index); 
+       //
+       // Add Time0 correction due unisochronity
+       // xyz[0] - pad row coordinate 
+       // xyz[1] - pad coordinate
+       // xyz[2] - is in now time bin coordinate system
+       Float_t correction =0;
+       if (calib->GetPadTime0()){
+         if (!calib->GetPadTime0()->GetCalROC(isec)) continue;   
+         Int_t npads = fTPCParam->GetNPads(isec,padrow);
+         //      Int_t pad  = TMath::Nint(xyz[1]+fTPCParam->GetNPads(isec,TMath::Nint(xyz[0]))*0.5);
+         // pad numbering from -npads/2 .. npads/2-1
+         Int_t pad  = TMath::Nint(xyz[1]+npads/2);
+         if (pad<0) pad=0;
+         if (pad>=npads) pad=npads-1;
+         correction = calib->GetPadTime0()->GetCalROC(isec)->GetValue(padrow,pad);
+         //      printf("%d\t%d\t%d\t%f\n",isec,padrow,pad,correction);
+         if (fDebugStreamer){
+           (*fDebugStreamer)<<"Time0"<<
+             "isec="<<isec<<
+             "padrow="<<padrow<<
+             "pad="<<pad<<
+             "x0="<<xyz[0]<<
+             "x1="<<xyz[1]<<
+             "x2="<<xyz[2]<<
+             "hit.="<<tpcHit<<
+             "cor="<<correction<<
+             "\n";
          }
-         
-         //---------------------------------
-         //  E x B effect at the wires
-         //---------------------------------
-         Int_t nw;
-         nw=(nwires+1)/2;
-         Float_t xx,dx;
-         for (Int_t nwire=1;nwire<=nwires;nwire++){
-           xx=(nwire-nw)*ww_pitch+
-             ((isec<13) ? pad_row_low[row_number]:pad_row_up[row_number]);
-           dx=xx-xyz[0];
-           if(TMath::Abs(dx) < 0.5*ww_pitch) {
-             xyz[1]=dx*omega_tau+xyz[1];
-             break;
-           }
-         } // end of loop over the wires
-         
-         TVector &v = *tr[row_number];
-         Int_t idx = 2*n_of_electrons[row_number]-1;
-         v(idx)=xyz[1];
-         v(idx+1)=xyz[2];
-       } // end of loop over electrons         
-      } // end of loop over hits  
-      
-      //
-      //  The track is finished 
-      //     
-      int trk=((AliTPChit*)fHits->UncheckedAt(0))->fTrack; //Y.Belikov
-      for(i=0;i<nrows;i++){
-       TVector &v = *tr[i];
-       if(n_of_electrons[i] >0) {
-         //        v(0)=(Float_t)(track+1); // track number
-          v(0)=(Float_t)(trk+1); // Y.Belikov 
-         tr[i]->ResizeTo(2*n_of_electrons[i]+1); // shrink if necessary
-         row[i]->Add(tr[i]); // add to the row-array
+       }
+       xyz[2]+=correction;
+       xyz[2]+=fTPCParam->GetNTBinsL1();    // adding Level 1 time bin offset
+       //
+       // Electron track time (for pileup simulation)
+       xyz[2]+=tpcHit->Time()/fTPCParam->GetTSample(); // adding time of flight
+       xyz[4] =0;
+
+       //
+       // row 0 - cross talk from the innermost row
+       // row fNRow+1 cross talk from the outermost row
+       rowNumber = index[2]+1; 
+       //transform position to local digit coordinates
+       //relative to nearest pad row 
+       if ((rowNumber<0)||rowNumber>fTPCParam->GetNRow(isec)+1) continue;
+       /*      Float_t x1,y1;
+       if (isec <fTPCParam->GetNInnerSector()) {
+         x1 = xyz[1]*fTPCParam->GetInnerPadPitchWidth();
+         y1 = fTPCParam->GetYInner(rowNumber);
        }
        else{
-         delete tr[i]; // delete TVector if empty
+         x1=xyz[1]*fTPCParam->GetOuterPadPitchWidth();
+         y1 = fTPCParam->GetYOuter(rowNumber);
        }
-      }   
-      delete [] tr; // delete track pointers  
-      delete [] n_of_electrons; // delete n_of_electrons array     
-    } //end of loop over tracks 
-    //---------------------------------------------------
-    //  Digitize the sector data, row by row
-    //---------------------------------------------------  
-    
-    printf("*** Digitizing sector number %d ***\n",isec);
-    
-    for(i=0;i<nrows;i++){
-      
-      DigSignal(isec,i,row[i]); 
-      gAlice->TreeD()->Fill();      
-      int ndig=fDigits->GetEntriesFast();
-      printf("*** Sector, row, digits %d %d %d ***\n",isec,i+1,ndig);
-      
-      ResetDigits();
-      
-      row[i]->Delete(); // delete objects in this array
-      delete row[i]; // delete the TObjArray itselves
+       // gain inefficiency at the wires edges - linear
+       x1=TMath::Abs(x1);
+       y1-=1.;
+       if(x1>y1) xyz[3]*=TMath::Max(1.e-6,(y1-x1+1.)); */
+       
+       nofElectrons[rowNumber]++;        
+       //----------------------------------
+       // Expand vector if necessary
+       //----------------------------------
+       if(nofElectrons[rowNumber]>120){
+         Int_t range = tracks[rowNumber]->GetNrows();
+         if((nofElectrons[rowNumber])>(range-1)/5){
+           
+           tracks[rowNumber]->ResizeTo(range+500); // Add 100 electrons
+         }
+       }
+       
+       TVector &v = *tracks[rowNumber];
+       Int_t idx = 5*nofElectrons[rowNumber]-4;
+       Real_t * position = &(((TVector&)v)(idx)); //make code faster
+       memcpy(position,xyz,5*sizeof(Float_t));
+       
+      } // end of loop over electrons
+
+      tpcHit = (AliTPChit*)NextHit();
       
-    } // end of digitization
-    
-    delete [] row; // delete vectors of pointers to sectors
-    
-  } //end of loop over sectors 
+    } // end of loop over hits
+  } // end of loop over tracks
+
+    //
+    //   store remaining track (the last one) if not empty
+    //
   
-}
+  for(i=0;i<nrows+2;i++){
+    if(nofElectrons[i]>0){
+      TVector &v = *tracks[i];
+      v(0) = previousTrack;
+      tracks[i]->ResizeTo(5*nofElectrons[i]+1); // shrink if necessary
+      row[i]->Add(tracks[i]);  
+    }
+    else{
+      delete tracks[i];
+      tracks[i]=0;
+    }  
+  }  
+  
+  delete [] tracks;
+  delete [] nofElectrons;
+
+} // end of MakeSector
+
 
 //_____________________________________________________________________________
 void AliTPC::Init()
@@ -1462,203 +2201,102 @@ void AliTPC::Init()
   //
   // Initialise TPC detector after definition of geometry
   //
-  Int_t i;
-  //
-  printf("\n");
-  for(i=0;i<35;i++) printf("*");
-  printf(" TPC_INIT ");
-  for(i=0;i<35;i++) printf("*");
-  printf("\n");
-  //
-  for(i=0;i<80;i++) printf("*");
-  printf("\n");
+  AliDebug(1,"*********************************************");
 }
 
-//_____________________________________________________________________________
-void AliTPC::MakeBranch(Option_t* option)
-{
-  //
-  // Create Tree branches for the TPC.
-  //
-  Int_t buffersize = 4000;
-  char branchname[10];
-  sprintf(branchname,"%s",GetName());
-
-  AliDetector::MakeBranch(option);
-
-  char *D = strstr(option,"D");
-
-  if (fDigits   && gAlice->TreeD() && D) {
-    gAlice->TreeD()->Branch(branchname,&fDigits, buffersize);
-    printf("Making Branch %s for digits\n",branchname);
-  }    
-
-  char *R = strstr(option,"R");
-
-  if (fClusters && gAlice->TreeR() && R) {
-    gAlice->TreeR()->Branch(branchname,&fClusters, buffersize);
-    printf("Making Branch %s for Clusters\n",branchname);
-  }    
-}
 //_____________________________________________________________________________
 void AliTPC::ResetDigits()
 {
   //
   // Reset number of digits and the digits array for this detector
-  // reset clusters
   //
   fNdigits   = 0;
   if (fDigits)   fDigits->Clear();
-  fNclusters = 0;
-  if (fClusters) fClusters->Clear();
 }
 
-//_____________________________________________________________________________
-void AliTPC::SetSecAL(Int_t sec)
-{
-  //
-  // Activate/deactivate selection for lower sectors
-  //
-  fSecAL = sec;
-}
 
-//_____________________________________________________________________________
-void AliTPC::SetSecAU(Int_t sec)
-{
-  //
-  // Activate/deactivate selection for upper sectors
-  //
-  fSecAU = sec;
-}
 
 //_____________________________________________________________________________
-void AliTPC::SetSecLows(Int_t s1,Int_t s2,Int_t s3,Int_t s4,Int_t s5, Int_t s6)
+void AliTPC::SetSens(Int_t sens)
 {
-  //
-  // Select active lower sectors
-  //
-  fSecLows[0] = s1;
-  fSecLows[1] = s2;
-  fSecLows[2] = s3;
-  fSecLows[3] = s4;
-  fSecLows[4] = s5;
-  fSecLows[5] = s6;
-}
 
-//_____________________________________________________________________________
-void AliTPC::SetSecUps(Int_t s1,Int_t s2,Int_t s3,Int_t s4,Int_t s5, Int_t s6,
-                       Int_t s7, Int_t s8 ,Int_t s9 ,Int_t s10, 
-                       Int_t s11 , Int_t s12)
-{
-  // 
-  // Select active upper sectors
-  //
-  fSecUps[0] = s1;
-  fSecUps[1] = s2;
-  fSecUps[2] = s3;
-  fSecUps[3] = s4;
-  fSecUps[4] = s5;
-  fSecUps[5] = s6;
-  fSecUps[6] = s7;
-  fSecUps[7] = s8;
-  fSecUps[8] = s9;
-  fSecUps[9] = s10;
-  fSecUps[10] = s11;
-  fSecUps[11] = s12;
-}
+  //-------------------------------------------------------------
+  // Activates/deactivates the sensitive strips at the center of
+  // the pad row -- this is for the space-point resolution calculations
+  //-------------------------------------------------------------
+
+  //-----------------------------------------------------------------
+  // Origin: Marek Kowalski  IFJ, Krakow, Marek.Kowalski@ifj.edu.pl
+  //-----------------------------------------------------------------
 
-//_____________________________________________________________________________
-void AliTPC::SetSens(Int_t sens)
-{
   fSens = sens;
 }
 
-//_____________________________________________________________________________
-void AliTPC::Streamer(TBuffer &R__b)
-{
-  //
-  // Stream an object of class AliTPC.
-  //
-   if (R__b.IsReading()) {
-      Version_t R__v = R__b.ReadVersion(); if (R__v) { }
-      AliDetector::Streamer(R__b);
-      if (R__v < 2) return;
-      R__b >> fNsectors;
-      R__b >> fNclusters;
-      R__b >> fNtracks;
-      fClustersIndex = new Int_t[fNsectors+1];
-      fDigitsIndex   = new Int_t[fNsectors+1];
-   } else {
-      R__b.WriteVersion(AliTPC::IsA());
-      AliDetector::Streamer(R__b);
-      R__b << fNsectors;
-      R__b << fNclusters;
-      R__b << fNtracks;
-   }
-}
-  
-ClassImp(AliTPCcluster)
  
-//_____________________________________________________________________________
-AliTPCcluster::AliTPCcluster(Float_t *hits, Int_t *lab)
+void AliTPC::SetSide(Float_t side=0.)
 {
-  //
-  // Creates a simulated cluster for the TPC
-  //
-  fTracks[0]  = lab[0];
-  fTracks[1]  = lab[1];
-  fTracks[2]  = lab[2];
-  fSector     = lab[3];
-  fPadRow     = lab[4];
-  fY          = hits[0];
-  fZ          = hits[1];
-  fQ          = hits[2];
-  fSigmaY2    = hits[3];
-  fSigmaZ2    = hits[4];
-}
+  // choice of the TPC side
+
+  fSide = side;
  
+}
 //_____________________________________________________________________________
-void AliTPCcluster::GetXYZ(Double_t& x, Double_t& y, Double_t& z) const 
+
+void AliTPC::TransportElectron(Float_t *xyz, Int_t *index)
 {
   //
-  // Returns centroid for of a simulated TPC cluster
+  // electron transport taking into account:
+  // 1. diffusion, 
+  // 2.ExB at the wires
+  // 3. nonisochronity
   //
-  Double_t alpha,xrow;
-  if (fSector<24) {
-    alpha=(fSector<12) ? fSector*alpha_low : (fSector-12)*alpha_low;
-    xrow=pad_row_low[fPadRow];
-  } else {
-    alpha=(fSector<48) ? (fSector-24)*alpha_up : (fSector-48)*alpha_up;
-    xrow=pad_row_up[fPadRow];
+  // xyz and index must be already transformed to system 1
+  //
+
+  fTPCParam->Transform1to2(xyz,index);  // mis-alignment applied in this step
+  
+  //add diffusion
+  Float_t driftl=xyz[2];
+  if(driftl<0.01) driftl=0.01;
+  driftl=TMath::Sqrt(driftl);
+  Float_t sigT = driftl*(fTPCParam->GetDiffT());
+  Float_t sigL = driftl*(fTPCParam->GetDiffL());
+  xyz[0]=gRandom->Gaus(xyz[0],sigT);
+  xyz[1]=gRandom->Gaus(xyz[1],sigT);
+  xyz[2]=gRandom->Gaus(xyz[2],sigL);
+
+  // ExB
+  
+  if (fTPCParam->GetMWPCReadout()==kTRUE){
+    Float_t dx = fTPCParam->Transform2to2NearestWire(xyz,index);
+    xyz[1]+=dx*(fTPCParam->GetOmegaTau());
   }
-  x=xrow*cos(alpha) - fY*sin(alpha);
-  y=xrow*sin(alpha) + fY*cos(alpha);
-  z=fZ;
-}
+  //add nonisochronity (not implemented yet) 
  
-ClassImp(AliTPCdigit)
-//_____________________________________________________________________________
-AliTPCdigit::AliTPCdigit(Int_t *tracks, Int_t *digits):
-  AliDigit(tracks)
+  
+}
+  
+ClassImp(AliTPChit)
+  //______________________________________________________________________
+  AliTPChit::AliTPChit()
+            :AliHit(),
+            fSector(0),
+            fPadRow(0),
+            fQ(0),
+            fTime(0)
 {
   //
-  // Creates a TPC digit object
+  // default
   //
-  fSector     = digits[0];
-  fPadRow     = digits[1];
-  fPad        = digits[2];
-  fTime       = digits[3];
-  fSignal     = digits[4];
-}
 
-ClassImp(AliTPChit)
+}
 //_____________________________________________________________________________
-AliTPChit::AliTPChit(Int_t shunt, Int_t track, Int_t *vol, Float_t *hits):
-AliHit(shunt,track)
+AliTPChit::AliTPChit(Int_t shunt, Int_t track, Int_t *vol, Float_t *hits)
+          :AliHit(shunt,track),
+            fSector(0),
+            fPadRow(0),
+            fQ(0),
+            fTime(0)
 {
   //
   // Creates a TPC hit object
@@ -1669,383 +2307,312 @@ AliHit(shunt,track)
   fY          = hits[1];
   fZ          = hits[2];
   fQ          = hits[3];
+  fTime       = hits[4];
 }
  
-ClassImp(AliTPCtrack)
-//_____________________________________________________________________________
-AliTPCtrack::AliTPCtrack(Float_t *hits)
-{
-  //
-  // Default creator for a TPC reconstructed track object
-  //
-  ref=hits[0]; // This is dummy code !
-}
+//________________________________________________________________________
+// Additional code because of the AliTPCTrackHitsV2
 
-AliTPCtrack::AliTPCtrack(const AliTPCcluster& c,const TVector& xx,
-                        const TMatrix& CC):
-  x(xx),C(CC),clusters(MAX_CLUSTER)
+void AliTPC::MakeBranch(Option_t *option)
 {
   //
-  // Standard creator for a TPC reconstructed track object
+  // Create a new branch in the current Root Tree
+  // The branch of fHits is automatically split
+  // MI change 14.09.2000
+  AliDebug(1,"");
+  if (fHitType<2) return;
+  char branchname[10];
+  sprintf(branchname,"%s2",GetName());  
+  //
+  // Get the pointer to the header
+  const char *cH = strstr(option,"H");
   //
-  chi2=0.;
-  int sec=c.fSector, row=c.fPadRow;
-  if (sec<24) { 
-    fAlpha=(sec%12)*alpha_low; ref=pad_row_low[0] + row*pad_pitch_l;
-  } else { 
-    fAlpha=(sec%24)*alpha_up;  ref=pad_row_up[0]  + row*pad_pitch_l;
+  if (fTrackHits   && fLoader->TreeH() && cH && fHitType&4) {
+    AliDebug(1,"Making branch for Type 4 Hits");
+    fLoader->TreeH()->Branch(branchname,"AliTPCTrackHitsV2",&fTrackHits,fBufferSize,99);
   }
-  clusters.AddLast((AliTPCcluster*)(&c));
+
+//   if (fTrackHitsOld   && fLoader->TreeH() && cH && fHitType&2) {    
+//     AliDebug(1,"Making branch for Type 2 Hits");
+//     AliObjectBranch * branch = new AliObjectBranch(branchname,"AliTPCTrackHits",&fTrackHitsOld, 
+//                                                    fLoader->TreeH(),fBufferSize,99);
+//     fLoader->TreeH()->GetListOfBranches()->Add(branch);
+//   } 
 }
 
-//_____________________________________________________________________________
-AliTPCtrack::AliTPCtrack(const AliTPCtrack& t) : x(t.x), C(t.C),
-  clusters(t.clusters.GetEntriesFast()) 
+void AliTPC::SetTreeAddress()
 {
-  //
-  // Copy creator for a TPC reconstructed track
-  //
-  ref=t.ref;
-  chi2=t.chi2;
-  fAlpha=t.fAlpha;
-  int n=t.clusters.GetEntriesFast();
-  for (int i=0; i<n; i++) clusters.AddLast(t.clusters.UncheckedAt(i));
+  //Sets tree address for hits  
+  if (fHitType<=1) {
+    if (fHits == 0x0 ) fHits = new TClonesArray("AliTPChit", 176);//skowron 20.06.03
+    AliDetector::SetTreeAddress();
+  }
+  if (fHitType>1) SetTreeAddress2();
 }
 
-//_____________________________________________________________________________
-Double_t AliTPCtrack::GetY(Double_t xk) const 
+void AliTPC::SetTreeAddress2()
 {
   //
-  //
-  //
-  Double_t c2=x(2)*xk - x(3);
-  if (TMath::Abs(c2) >= 0.999) {
-    if (*this>10) cerr<<*this<<" AliTPCtrack warning: No y for this x !\n";
-    return 0.;
+  // Set branch address for the TrackHits Tree
+  // 
+  AliDebug(1,"");
+  
+  TBranch *branch;
+  char branchname[20];
+  sprintf(branchname,"%s2",GetName());
+  //
+  // Branch address for hit tree
+  TTree *treeH = fLoader->TreeH();
+  if ((treeH)&&(fHitType&4)) {
+    branch = treeH->GetBranch(branchname);
+    if (branch) {
+      branch->SetAddress(&fTrackHits);
+      AliDebug(1,"fHitType&4 Setting");
+    }
+    else 
+      AliDebug(1,"fHitType&4 Failed (can not find branch)");
+    
   }
-  Double_t c1=x(2)*ref - x(3);
-  Double_t r1=sqrt(1.-c1*c1), r2=sqrt(1.-c2*c2);
-  Double_t dx=xk-ref;
-  return x(0) + dx*(c1+c2)/(r1+r2);
+ //  if ((treeH)&&(fHitType&2)) {
+//     branch = treeH->GetBranch(branchname);
+//     if (branch) {
+//       branch->SetAddress(&fTrackHitsOld);
+//       AliDebug(1,"fHitType&2 Setting");
+//     }
+//     else
+//       AliDebug(1,"fHitType&2 Failed (can not find branch)");
+//   }
 }
 
-//_____________________________________________________________________________
-int AliTPCtrack::PropagateTo(Double_t xk,Double_t x0,Double_t rho,Double_t pm)
+void AliTPC::FinishPrimary()
 {
+  if (fTrackHits &&fHitType&4)      fTrackHits->FlushHitStack();  
+  //  if (fTrackHitsOld && fHitType&2)  fTrackHitsOld->FlushHitStack();  
+}
+
+
+void AliTPC::AddHit2(Int_t track, Int_t *vol, Float_t *hits)
+{ 
   //
-  // Propagate a TPC reconstructed track
-  //
-  if (TMath::Abs(x(2)*xk - x(3)) >= 0.999) {
-    if (*this>3) cerr<<*this<<" AliTPCtrack warning: Propagation failed !\n";
-    return 0;
-  }
-  
-  Double_t x1=ref, x2=x1+0.5*(xk-x1), dx=x2-x1, y1=x(0), z1=x(1);
-  Double_t c1=x(2)*x1 - x(3), r1=sqrt(1.- c1*c1);
-  Double_t c2=x(2)*x2 - x(3), r2=sqrt(1.- c2*c2);
-  
-  x(0) += dx*(c1+c2)/(r1+r2);
-  x(1) += dx*(c1+c2)/(c1*r2 + c2*r1)*x(4);
-  
-  TMatrix F(5,5); F.UnitMatrix();
-  Double_t rr=r1+r2, cc=c1+c2, xx=x1+x2;
-  F(0,2)= dx*(rr*xx + cc*(c1*x1/r1+c2*x2/r2))/(rr*rr);
-  F(0,3)=-dx*(2*rr + cc*(c1/r1 + c2/r2))/(rr*rr);
-  Double_t cr=c1*r2+c2*r1;
-  F(1,2)= dx*x(4)*(cr*xx-cc*(r1*x2-c2*c1*x1/r1+r2*x1-c1*c2*x2/r2))/(cr*cr);
-  F(1,3)=-dx*x(4)*(2*cr + cc*(c2*c1/r1-r1 + c1*c2/r2-r2))/(cr*cr);
-  F(1,4)= dx*cc/cr; 
-  TMatrix tmp(F,TMatrix::kMult,C);
-  C.Mult(tmp,TMatrix(TMatrix::kTransposed,F));
-  
-  ref=x2;
-  
-  //Multiple scattering******************
-  Double_t ey=x(2)*ref - x(3);
-  Double_t ex=sqrt(1-ey*ey);
-  Double_t ez=x(4);
-  TMatrix Q(5,5); Q=0.;
-  Q(2,2)=ez*ez+ey*ey;   Q(2,3)=-ex*ey;       Q(2,4)=-ex*ez;
-  Q(3,2)=Q(2,3);        Q(3,3)= ez*ez+ex*ex; Q(3,4)=-ey*ez;
-  Q(4,2)=Q(2,4);        Q(4,3)= Q(3,4);      Q(4,4)=1.;
-  
-  F=0;
-  F(2,2)=-x(2)*ex;          F(2,3)=-x(2)*ey;
-  F(3,2)=-ex*(x(2)*ref-ey); F(3,3)=-(1.+ x(2)*ref*ey - ey*ey);
-  F(4,2)=-ez*ex;            F(4,3)=-ez*ey;           F(4,4)=1.;
-  
-  tmp.Mult(F,Q);
-  Q.Mult(tmp,TMatrix(TMatrix::kTransposed,F));
-  
-  Double_t p2=GetPt()*GetPt()*(1.+x(4)*x(4));
-  Double_t beta2=p2/(p2 + pm*pm);
-  Double_t d=sqrt((x1-ref)*(x1-ref)+(y1-x(0))*(y1-x(0))+(z1-x(1))*(z1-x(1)));
-  d*=2.;
-  Double_t theta2=14.1*14.1/(beta2*p2*1e6)*d/x0*rho;
-  Q*=theta2;
-  C+=Q;
-  
-  //Energy losses************************
-  Double_t dE=0.153e-3/beta2*(log(5940*beta2/(1-beta2)) - beta2)*d*rho;
-  if (x1 < x2) dE=-dE;
-  x(2)*=(1.- sqrt(p2+pm*pm)/p2*dE);
-  
-  x1=ref; x2=xk; y1=x(0); z1=x(1);
-  c1=x(2)*x1 - x(3); r1=sqrt(1.- c1*c1);
-  c2=x(2)*x2 - x(3); r2=sqrt(1.- c2*c2);
-  
-  x(0) += dx*(c1+c2)/(r1+r2);
-  x(1) += dx*(c1+c2)/(c1*r2 + c2*r1)*x(4);
-  
-  F.UnitMatrix();
-  rr=r1+r2; cc=c1+c2; xx=x1+x2;
-  F(0,2)= dx*(rr*xx + cc*(c1*x1/r1+c2*x2/r2))/(rr*rr);
-  F(0,3)=-dx*(2*rr + cc*(c1/r1 + c2/r2))/(rr*rr);
-  cr=c1*r2+c2*r1;
-  F(1,2)= dx*x(4)*(cr*xx-cc*(r1*x2-c2*c1*x1/r1+r2*x1-c1*c2*x2/r2))/(cr*cr);
-  F(1,3)=-dx*x(4)*(2*cr + cc*(c2*c1/r1-r1 + c1*c2/r2-r2))/(cr*cr);
-  F(1,4)= dx*cc/cr; 
-  tmp.Mult(F,C);
-  C.Mult(tmp,TMatrix(TMatrix::kTransposed,F));
-  
-  ref=x2;
+  // add hit to the list
+
+  Int_t rtrack;
+  if (fIshunt) {
+    int primary = gAlice->GetMCApp()->GetPrimary(track);
+    gAlice->GetMCApp()->Particle(primary)->SetBit(kKeepBit);
+    rtrack=primary;
+  } else {
+    rtrack=track;
+    gAlice->GetMCApp()->FlagTrack(track);
+  }  
+  if (fTrackHits && fHitType&4) 
+    fTrackHits->AddHitKartez(vol[0],rtrack, hits[0],
+                             hits[1],hits[2],(Int_t)hits[3],hits[4]);
+ //  if (fTrackHitsOld &&fHitType&2 ) 
+//     fTrackHitsOld->AddHitKartez(vol[0],rtrack, hits[0],
+//                                 hits[1],hits[2],(Int_t)hits[3]);
   
-  return 1;
 }
 
-//_____________________________________________________________________________
-void AliTPCtrack::PropagateToVertex(Double_t x0,Double_t rho,Double_t pm) 
+void AliTPC::ResetHits()
+{ 
+  if (fHitType&1) AliDetector::ResetHits();
+  if (fHitType>1) ResetHits2();
+}
+
+void AliTPC::ResetHits2()
 {
   //
-  // Propagate a reconstructed track from the vertex
-  //
-  Double_t c=x(2)*ref - x(3);
-  Double_t tgf=-x(3)/(x(2)*x(0) + sqrt(1-c*c));
-  Double_t snf=tgf/sqrt(1.+ tgf*tgf);
-  Double_t xv=(x(3)+snf)/x(2);
-  PropagateTo(xv,x0,rho,pm);
-}
+  //reset hits
+  if (fTrackHits && fHitType&4) fTrackHits->Clear();
+  // if (fTrackHitsOld && fHitType&2) fTrackHitsOld->Clear();
 
-//_____________________________________________________________________________
-void AliTPCtrack::Update(const AliTPCcluster *c, Double_t chisq)
+}   
+
+AliHit* AliTPC::FirstHit(Int_t track)
+{
+  if (fHitType>1) return FirstHit2(track);
+  return AliDetector::FirstHit(track);
+}
+AliHit* AliTPC::NextHit()
 {
   //
-  // Update statistics for a reconstructed TPC track
+  // gets next hit
   //
-  TMatrix H(2,5); H.UnitMatrix();
-  TMatrix Ht(TMatrix::kTransposed,H);
-  TVector m(2);   m(0)=c->fY; m(1)=c->fZ; 
-  TMatrix V(2,2); V(0,0)=c->fSigmaY2; V(0,1)=0.; V(1,0)=0.; V(1,1)=c->fSigmaZ2;
-
-  TMatrix tmp(H,TMatrix::kMult,C);
-  TMatrix R(tmp,TMatrix::kMult,Ht); R+=V;
-  
-  Double_t det=(Double_t)R(0,0)*R(1,1) - (Double_t)R(0,1)*R(1,0);
-  R(0,1)=R(0,0); R(0,0)=R(1,1); R(1,1)=R(0,1); 
-  R(1,0)*=-1; R(0,1)=R(1,0);
-  R*=1./det;
-  
-  //R.Invert();
-  
-  TMatrix K(C,TMatrix::kMult,Ht); K*=R;
-  
-  TVector savex=x;
-  x*=H; x-=m; x*=-1; x*=K; x+=savex;
-  if (TMath::Abs(x(2)*ref-x(3)) >= 0.999) {
-    if (*this>3) cerr<<*this<<" AliTPCtrack warning: Filtering failed !\n";
-    x=savex;
-    return;
-  }
+  if (fHitType>1) return NextHit2();
   
-  TMatrix saveC=C;
-  C.Mult(K,tmp); C-=saveC; C*=-1;
-  
-  clusters.AddLast((AliTPCcluster*)c);
-  chi2 += chisq;
+  return AliDetector::NextHit();
 }
 
-//_____________________________________________________________________________
-int AliTPCtrack::Rotate(Double_t alpha)
+AliHit* AliTPC::FirstHit2(Int_t track)
 {
   //
-  // Rotate a reconstructed TPC track
-  //
-  fAlpha += alpha;
-  
-  Double_t x1=ref, y1=x(0);
-  Double_t ca=cos(alpha), sa=sin(alpha);
-  Double_t r1=x(2)*ref - x(3);
-  
-  ref = x1*ca + y1*sa;
-  x(0)=-x1*sa + y1*ca;
-  x(3)=x(3)*ca + (x(2)*y1 + sqrt(1.- r1*r1))*sa;
-  
-  Double_t r2=x(2)*ref - x(3);
-  if (TMath::Abs(r2) >= 0.999) {
-    if (*this>3) cerr<<*this<<" AliTPCtrack warning: Rotation failed !\n";
-    return 0;
+  // Initialise the hit iterator
+  // Return the address of the first hit for track
+  // If track>=0 the track is read from disk
+  // while if track<0 the first hit of the current
+  // track is returned
+  // 
+  if(track>=0) {
+    gAlice->GetMCApp()->ResetHits();
+    fLoader->TreeH()->GetEvent(track);
   }
-  
-  Double_t y0=x(0) + sqrt(1.- r2*r2)/x(2);
-  if ((x(0)-y0)*x(2) >= 0.) {
-    if (*this>3) cerr<<*this<<" AliTPCtrack warning: Rotation failed !!!\n";
-    return 0;
+  //
+  if (fTrackHits && fHitType&4) {
+    fTrackHits->First();
+    return fTrackHits->GetHit();
   }
-  
-  TMatrix F(5,5); F.UnitMatrix();
-  F(0,0)=ca;
-  F(3,0)=x(2)*sa; 
-  F(3,2)=(y1 - r1*x1/sqrt(1.- r1*r1))*sa; 
-  F(3,3)= ca + sa*r1/sqrt(1.- r1*r1);
-  TMatrix tmp(F,TMatrix::kMult,C); 
-  // Double_t dy2=C(0,0);
-  C.Mult(tmp,TMatrix(TMatrix::kTransposed,F));
-  // C(0,0)+=dy2*sa*sa*r1*r1/(1.- r1*r1);
-  // C(1,1)+=dy2*sa*sa*x(4)*x(4)/(1.- r1*r1);
-  
-  return 1;
+ //  if (fTrackHitsOld && fHitType&2) {
+//     fTrackHitsOld->First();
+//     return fTrackHitsOld->GetHit();
+//   }
+
+  else return 0;
 }
 
-//_____________________________________________________________________________
-void AliTPCtrack::UseClusters() const 
+AliHit* AliTPC::NextHit2()
 {
   //
-  //
-  //
-  int num_of_clusters=clusters.GetEntriesFast();
-  for (int i=0; i<num_of_clusters; i++) {
-    //if (i<=14) continue;
-    AliTPCcluster *c=(AliTPCcluster*)clusters.UncheckedAt(i);
-    c->Use();   
+  //Return the next hit for the current track
+
+
+//   if (fTrackHitsOld && fHitType&2) {
+//     fTrackHitsOld->Next();
+//     return fTrackHitsOld->GetHit();
+//   }
+  if (fTrackHits) {
+    fTrackHits->Next();
+    return fTrackHits->GetHit();
   }
+  else 
+    return 0;
 }
 
-//_____________________________________________________________________________
-Double_t AliTPCtrack::GetPredictedChi2(const AliTPCcluster *c) const 
+void AliTPC::RemapTrackHitIDs(Int_t *map)
 {
   //
-  // Calculate chi2 for a reconstructed TPC track
-  //
-  TMatrix H(2,5); H.UnitMatrix();
-  TVector m(2);   m(0)=c->fY; m(1)=c->fZ; 
-  TMatrix V(2,2); V(0,0)=c->fSigmaY2; V(0,1)=0.; V(1,0)=0.; V(1,1)=c->fSigmaZ2;
-  TVector res=x;  res*=H; res-=m; //res*=-1; 
-  TMatrix tmp(H,TMatrix::kMult,C);
-  TMatrix R(tmp,TMatrix::kMult,TMatrix(TMatrix::kTransposed,H)); R+=V;
-  
-  Double_t det=(Double_t)R(0,0)*R(1,1) - (Double_t)R(0,1)*R(1,0);
-  if (TMath::Abs(det) < 1.e-10) {
-    if (*this>3) cerr<<*this<<" AliTPCtrack warning: Singular matrix !\n";
-    return 1e10;
+  // remapping
+  //
+  if (!fTrackHits) return;
+  
+//   if (fTrackHitsOld && fHitType&2){
+//     AliObjectArray * arr = fTrackHitsOld->fTrackHitsInfo;
+//     for (UInt_t i=0;i<arr->GetSize();i++){
+//       AliTrackHitsInfo * info = (AliTrackHitsInfo *)(arr->At(i));
+//       info->fTrackID = map[info->fTrackID];
+//     }
+//   }
+//  if (fTrackHitsOld && fHitType&4){
+  if (fTrackHits && fHitType&4){
+    TClonesArray * arr = fTrackHits->GetArray();;
+    for (Int_t i=0;i<arr->GetEntriesFast();i++){
+      AliTrackHitsParamV2 * info = (AliTrackHitsParamV2 *)(arr->At(i));
+      info->SetTrackID(map[info->GetTrackID()]);
+    }
   }
-  R(0,1)=R(0,0); R(0,0)=R(1,1); R(1,1)=R(0,1); 
-  R(1,0)*=-1; R(0,1)=R(1,0);
-  R*=1./det;
-  
-  //R.Invert();
-  
-  TVector r=res;
-  res*=R;
-  return r*res;
 }
 
-//_____________________________________________________________________________
-int AliTPCtrack::GetLab() const 
+Bool_t   AliTPC::TrackInVolume(Int_t id,Int_t track)
 {
-  //
-  //
-  //
-  int lab = 0;
-  struct {
-    int lab;
-    int max;
-  } s[MAX_CLUSTER]={{0,0}};
-  
-  int i;
-  int num_of_clusters=clusters.GetEntriesFast();
-  for (i=0; i<num_of_clusters; i++) {
-    AliTPCcluster *c=(AliTPCcluster*)clusters.UncheckedAt(i);
-    lab=c->fTracks[0]; if (lab<0) lab=-lab;
-    int j;
-    for (j=0; j<MAX_CLUSTER; j++)
-      if (s[j].lab==lab || s[j].max==0) break;
-    s[j].lab=lab;
-    s[j].max++;
+  //return bool information - is track in given volume
+  //load only part of the track information 
+  //return true if current track is in volume
+  //
+  //  return kTRUE;
+ //  if (fTrackHitsOld && fHitType&2) {
+//     TBranch * br = fLoader->TreeH()->GetBranch("fTrackHitsInfo");
+//     br->GetEvent(track);
+//     AliObjectArray * ar = fTrackHitsOld->fTrackHitsInfo;
+//     for (UInt_t j=0;j<ar->GetSize();j++){
+//       if (  ((AliTrackHitsInfo*)ar->At(j))->fVolumeID==id) return kTRUE;
+//     } 
+//   }
+
+  if (fTrackHits && fHitType&4) {
+    TBranch * br1 = fLoader->TreeH()->GetBranch("fVolumes");
+    TBranch * br2 = fLoader->TreeH()->GetBranch("fNVolumes");    
+    br2->GetEvent(track);
+    br1->GetEvent(track);    
+    Int_t *volumes = fTrackHits->GetVolumes();
+    Int_t nvolumes = fTrackHits->GetNVolumes();
+    if (!volumes && nvolumes>0) {
+      AliWarning(Form("Problematic track\t%d\t%d",track,nvolumes));
+      return kFALSE;
+    }
+    for (Int_t j=0;j<nvolumes; j++)
+      if (volumes[j]==id) return kTRUE;    
   }
-  
-  int max=0;
-  for (i=0; i<num_of_clusters; i++) 
-    if (s[i].max>max) {max=s[i].max; lab=s[i].lab;}
-  if (lab>0) lab--;
-  
-  if (1.-float(max)/num_of_clusters > 0.10) return -lab;
-  
-  if (num_of_clusters < 6) return lab;
-  
-  max=0;
-  for (i=1; i<=6; i++) {
-    AliTPCcluster *c=(AliTPCcluster*)clusters.UncheckedAt(num_of_clusters-i);
-    if (lab != TMath::Abs(c->fTracks[0])-1
-       && lab != TMath::Abs(c->fTracks[1])-1
-       && lab != TMath::Abs(c->fTracks[2])-1
-       ) max++;
+
+  if (fHitType&1) {
+    TBranch * br = fLoader->TreeH()->GetBranch("fSector");
+    br->GetEvent(track);
+    for (Int_t j=0;j<fHits->GetEntriesFast();j++){
+      if (  ((AliTPChit*)fHits->At(j))->fSector==id) return kTRUE;
+    } 
   }
-  if (max>3) return -lab;
-  
-  return lab;
+  return kFALSE;  
+
 }
 
-//_____________________________________________________________________________
-void AliTPCtrack::GetPxPyPz(Double_t& px, Double_t& py, Double_t& pz) const 
+
+AliLoader* AliTPC::MakeLoader(const char* topfoldername)
 {
-  //
-  // Get reconstructed TPC track momentum
-  //
-  Double_t pt=0.3*FIELD/TMath::Abs(x(2))/100; // GeV/c
-  Double_t r=x(2)*ref-x(3);
-  Double_t y0=x(0) + sqrt(1.- r*r)/x(2);
-  px=-pt*(x(0)-y0)*x(2);    //cos(phi);
-  py=-pt*(x(3)-ref*x(2));   //sin(phi);
-  pz=pt*x(4);
-  Double_t tmp=px*TMath::Cos(fAlpha) - py*TMath::Sin(fAlpha);
-  py=px*TMath::Sin(fAlpha) + py*TMath::Cos(fAlpha);
-  px=tmp;  
+  //Makes TPC loader
+  fLoader = new AliTPCLoader(GetName(),topfoldername);
+  return fLoader;
 }
 
-//_____________________________________________________________________________
+////////////////////////////////////////////////////////////////////////
+AliTPCParam* AliTPC::LoadTPCParam(TFile *file) {
 //
-//     Classes for internal tracking use
+// load TPC paarmeters from a given file or create new if the object
+// is not found there
+// 12/05/2003 This method should be moved to the AliTPCLoader
+// and one has to decide where to store the TPC parameters
+// M.Kowalski
+  char paramName[50];
+  sprintf(paramName,"75x40_100x60_150x60");
+  AliTPCParam *paramTPC=(AliTPCParam*)file->Get(paramName);
+  if (paramTPC) {
+    AliDebugClass(1,Form("TPC parameters %s found.",paramName));
+  } else {
+    AliWarningClass("TPC parameters not found. Create new (they may be incorrect)");
+    //paramTPC = new AliTPCParamSR;
+    paramTPC = AliTPCcalibDB::Instance()->GetParameters();
+    if (!paramTPC->IsGeoRead()){
+      //
+      // read transformation matrices for gGeoManager
+      //
+      paramTPC->ReadGeoMatrices();
+    }
+  
+  }
+  return paramTPC;
+
+// the older version of parameters can be accessed with this code.
+// In some cases, we have old parameters saved in the file but 
+// digits were created with new parameters, it can be distinguish 
+// by the name of TPC TreeD. The code here is just for the case 
+// we would need to compare with old data, uncomment it if needed.
 //
+//  char paramName[50];
+//  sprintf(paramName,"75x40_100x60");
+//  AliTPCParam *paramTPC=(AliTPCParam*)in->Get(paramName);
+//  if (paramTPC) {
+//    cout<<"TPC parameters "<<paramName<<" found."<<endl;
+//  } else {
+//    sprintf(paramName,"75x40_100x60_150x60");
+//    paramTPC=(AliTPCParam*)in->Get(paramName);
+//    if (paramTPC) {
+//     cout<<"TPC parameters "<<paramName<<" found."<<endl;
+//    } else {
+//     cerr<<"TPC parameters not found. Create new (they may be incorrect)."
+//         <<endl;    
+//     paramTPC = new AliTPCParamSR;
+//    }
+//  }
+//  return paramTPC;
 
-//_____________________________________________________________________________
-void AliTPCRow::InsertCluster(const AliTPCcluster* c) 
-{
-  //
-  // Insert a cluster in the list
-  //
-  if (num_of_clusters==MAX_CLUSTER_PER_ROW) {
-    cerr<<"AliTPCRow::InsertCluster(): Too many clusters !\n"; return;
-  }
-  if (num_of_clusters==0) {clusters[num_of_clusters++]=c; return;}
-  int i=Find(c->fY);
-  memmove(clusters+i+1 ,clusters+i,(num_of_clusters-i)*sizeof(AliTPCcluster*));
-  clusters[i]=c; num_of_clusters++;
 }
 
-//_____________________________________________________________________________
-int AliTPCRow::Find(Double_t y) const 
-{
-  //
-  //
-  //
-  if (y <= clusters[0]->fY) return 0;
-  if (y > clusters[num_of_clusters-1]->fY) return num_of_clusters;
-  int b=0, e=num_of_clusters-1, m=(b+e)/2;
-  for (; b<e; m=(b+e)/2) {
-    if (y > clusters[m]->fY) b=m+1;
-    else e=m; 
-  }
-  return m;
-}
+