]> git.uio.no Git - u/mrichter/AliRoot.git/blobdiff - TFluka/TFluka.cxx
Correction in ion definition.
[u/mrichter/AliRoot.git] / TFluka / TFluka.cxx
index e3e4be18924a1aaeace909eb1413d905380af7b3..81b5a1bd9ffdf23d25f3a05050279db1b81eee7f 100644 (file)
 //
 
 #include <Riostream.h>
+#include <TList.h>
 
 #include "TFluka.h"
+#include "TFlukaIon.h"
 #include "TFlukaCodes.h"
 #include "TCallf77.h"      //For the fortran calls
 #include "Fdblprc.h"       //(DBLPRC) fluka common
@@ -48,6 +50,7 @@
 #include "Fstepsz.h"       //(STEPSZ) fluka common
 #include "Fopphst.h"       //(OPPHST) fluka common
 #include "Fltclcm.h"       //(LTCLCM) fluka common
+#include "Falldlt.h"       //(ALLDLT) fluka common
 
 #include "TVirtualMC.h"
 #include "TMCProcess.h"
@@ -62,6 +65,9 @@
 #include "TLorentzVector.h"
 #include "TArrayI.h"
 #include "TArrayD.h"
+#include "TDatabasePDG.h"
+#include "TStopwatch.h"
+
 
 // Fluka methods that may be needed.
 #ifndef WIN32 
@@ -71,6 +77,9 @@
 # define fluka_closeinp fluka_closeinp_
 # define mcihad mcihad_
 # define mpdgha mpdgha_
+# define newplo newplo_
+# define genout genout_
+# define flkend flkend_
 #else 
 # define flukam  FLUKAM
 # define fluka_openinp FLUKA_OPENINP
@@ -79,6 +88,8 @@
 # define mcihad MCIHAD
 # define mpdgha MPDGHA
 # define newplo NEWPLO
+# define genout GENOUT
+# define flkend FLKEND
 #endif
 
 extern "C" 
@@ -88,6 +99,8 @@ extern "C"
   //
   void type_of_call flukam(const int&);
   void type_of_call newplo();
+  void type_of_call genout();
+  void type_of_call flkend();
   void type_of_call fluka_openinp(const int&, DEFCHARA);
   void type_of_call fluka_openout(const int&, DEFCHARA);
   void type_of_call fluka_closeinp(const int&);
@@ -107,79 +120,114 @@ ClassImp(TFluka)
 TFluka::TFluka()
   :TVirtualMC(),
    fVerbosityLevel(0),
+   fNEvent(0),
    fInputFileName(""),
+   fCoreInputFileName(""),
+   fCaller(kNoCaller),
+   fIcode(kNoProcess),
+   fNewReg(-1),
+   fRull(0),
+   fXsco(0),
+   fYsco(0),
+   fZsco(0),
+   fPItime(0),
+   fPIlength(0),
+   fNPI(0),
+   fTrackIsEntering(kFALSE),
+   fTrackIsExiting(kFALSE),
+   fTrackIsNew(kFALSE),
+   fFieldFlag(kTRUE),
+   fDummyBoundary(kFALSE),
+   fStopped(kFALSE),
+   fStopEvent(kFALSE),
+   fStopRun(kFALSE),
+   fPrimaryElectronIndex(-1),
+   fLowEnergyNeutronTransport(kFALSE),
+   fMaterials(0),
+   fNVolumes(0),
+   fCurrentFlukaRegion(-1),
+   fNCerenkov(0),
+   fGeom(0),
+   fMCGeo(0),
    fUserConfig(0), 
-   fUserScore(0)
+   fUserScore(0),
+   fUserIons(0)
 { 
   //
   // Default constructor
   //
-   fGeneratePemf = kFALSE;
-   fNVolumes = 0;
-   fCurrentFlukaRegion = -1;
-   fNewReg = -1;
-   fGeom = 0;
-   fMCGeo = 0;
-   fMaterials = 0;
-   fDummyBoundary = 0;
-   fFieldFlag = 1;
-   fStopped   = 0;
-   fStopEvent = 0;
-   fStopRun   = 0;
-   fNEvent    = 0;
+    for (Int_t i = 0; i < 4; i++) fPint[i] = 0.;
 } 
  
 //______________________________________________________________________________ 
 TFluka::TFluka(const char *title, Int_t verbosity, Bool_t isRootGeometrySupported)
   :TVirtualMC("TFluka",title, isRootGeometrySupported),
    fVerbosityLevel(verbosity),
+   fNEvent(0),
    fInputFileName(""),
-   fTrackIsEntering(0),
-   fTrackIsExiting(0),
-   fTrackIsNew(0),
+   fCoreInputFileName(""),
+   fCaller(kNoCaller),
+   fIcode(kNoProcess),
+   fNewReg(-1),
+   fRull(0),
+   fXsco(0),
+   fYsco(0),
+   fZsco(0),
+   fPItime(0),
+   fPIlength(0),
+   fNPI(0),
+   fTrackIsEntering(kFALSE),
+   fTrackIsExiting(kFALSE),
+   fTrackIsNew(kFALSE),
+   fFieldFlag(kTRUE),
+   fDummyBoundary(kFALSE),
+   fStopped(kFALSE),
+   fStopEvent(kFALSE),
+   fStopRun(kFALSE),
+   fPrimaryElectronIndex(-1),
+   fLowEnergyNeutronTransport(kFALSE),
+   fMaterials(0),
+   fNVolumes(0),
+   fCurrentFlukaRegion(-1),
+   fNCerenkov(0),
+   fGeom(0),
+   fMCGeo(0),
    fUserConfig(new TObjArray(100)),
-   fUserScore(new TObjArray(100)) 
+   fUserScore(new TObjArray(100)),
+   fUserIons(0)
 {
   // create geometry interface
+    for (Int_t i = 0; i < 4; i++) fPint[i] = 0.;
+    
    if (fVerbosityLevel >=3)
        cout << "<== TFluka::TFluka(" << title << ") constructor called." << endl;
    SetCoreInputFileName();
    SetInputFileName();
-   SetGeneratePemf(kFALSE);
-   fNVolumes      = 0;
-   fCurrentFlukaRegion = -1;
-   fNewReg = -1;
-   fDummyBoundary = 0;
-   fFieldFlag = 1;
-   fGeneratePemf = kFALSE;
-   fMCGeo = new TGeoMCGeometry("MCGeo", "TGeo Implementation of VirtualMCGeometry", kTRUE);
+   fMCGeo = new TGeoMCGeometry("MCGeo", "TGeo Implementation of VirtualMCGeometry", kFALSE);
    fGeom  = new TFlukaMCGeometry("geom", "FLUKA VMC Geometry");
    if (verbosity > 2) fGeom->SetDebugMode(kTRUE);
-   fMaterials = 0;
-   fStopped   = 0;
-   fStopEvent = 0;
-   fStopRun   = 0;
-   fNEvent    = 0;
    PrintHeader();
 }
 
 //______________________________________________________________________________ 
-TFluka::~TFluka() {
-// Destructor
+TFluka::~TFluka()
+{
+    // Destructor
     if (fVerbosityLevel >=3)
-       cout << "<== TFluka::~TFluka() destructor called." << endl;
+        cout << "<== TFluka::~TFluka() destructor called." << endl;
+    if (fMaterials) delete [] fMaterials;
     
-    delete fGeom;
-    delete fMCGeo;
+//    delete fGeom;
+//    delete fMCGeo;
     
     if (fUserConfig) {
-       fUserConfig->Delete();
-       delete fUserConfig;
+        fUserConfig->Delete();
+        delete fUserConfig;
     }
     
     if (fUserScore) {
-       fUserScore->Delete();
-       delete fUserScore;
+        fUserScore->Delete();
+        delete fUserScore;
     }
 }
 
@@ -214,7 +262,13 @@ void TFluka::Init() {
     }
 
     fApplication->InitGeometry();
-    
+    fApplication->ConstructOpGeometry();
+    //
+    // Add ions to PDG Data base
+    //
+     AddParticlesToPdgDataBase();
+     fApplication->AddIons();
+    //
 }
 
 
@@ -225,9 +279,10 @@ void TFluka::FinishGeometry() {
 //
   if (fVerbosityLevel >=3) {
     cout << "==> TFluka::FinishGeometry() called." << endl;
-    printf("----FinishGeometry - nothing to do with TGeo\n");
+    printf("----FinishGeometry - applying misalignment if any\n");
     cout << "<== TFluka::FinishGeometry() called." << endl;
   }  
+  TVirtualMCApplication::Instance()->MisalignGeometry();
 } 
 
 //______________________________________________________________________________ 
@@ -237,64 +292,44 @@ void TFluka::BuildPhysics() {
 //
     
     if (fVerbosityLevel >=3)
-       cout << "==> TFluka::BuildPhysics() called." << endl;
+        cout << "==> TFluka::BuildPhysics() called." << endl;
 
     
     if (fVerbosityLevel >=3) {
-       TList *medlist = gGeoManager->GetListOfMedia();
-       TIter next(medlist);
-       TGeoMedium*   med = 0x0;
-       TGeoMaterial* mat = 0x0;
-       Int_t ic = 0;
-       
-       while((med = (TGeoMedium*)next()))
-       {
-           mat = med->GetMaterial();
-           printf("Medium %5d %12s %5d %5d\n", ic, (med->GetName()), med->GetId(), mat->GetIndex());
-           ic++;
-       }
+        TList *medlist = gGeoManager->GetListOfMedia();
+        TIter next(medlist);
+        TGeoMedium*   med = 0x0;
+        TGeoMaterial* mat = 0x0;
+        Int_t ic = 0;
+        
+        while((med = (TGeoMedium*)next()))
+        {
+            mat = med->GetMaterial();
+            printf("Medium %5d %12s %5d %5d\n", ic, (med->GetName()), med->GetId(), mat->GetIndex());
+            ic++;
+        }
     }
     
-    //
-    // At this stage we have the information on materials and cuts available.
-    // Now create the pemf file
-    
-    if (fGeneratePemf) fGeom->CreatePemfFile();
-    
-    //
+
     // Prepare input file with the current physics settings
     
     InitPhysics(); 
-    
-    cout << "\t* InitPhysics() - Prepare input file was called" << endl; 
-    
-    if (fVerbosityLevel >=2)
-       cout << "\t* Changing lfdrtr = (" << (GLOBAL.lfdrtr?'T':'F')
-            << ") in fluka..." << endl;
-    GLOBAL.lfdrtr = true;
-    
-    if (fVerbosityLevel >=2)
-       cout << "\t* Opening file " << fInputFileName << endl;
+//  Open fortran files    
     const char* fname = fInputFileName;
-    
     fluka_openinp(lunin, PASSCHARA(fname));
     fluka_openout(11, PASSCHARA("fluka.out"));
-    
-    if (fVerbosityLevel >=2)
-       cout << "\t* Calling flukam..." << endl;
+//  Read input cards    
+    cout << "==> TFluka::BuildPhysics() Read input cards." << endl;
+    TStopwatch timer;
+    timer.Start();
+    GLOBAL.lfdrtr = true;
     flukam(1);
-    
-    if (fVerbosityLevel >=2)
-       cout << "\t* Closing file " << fInputFileName << endl;
+    cout << "<== TFluka::BuildPhysics() Read input cards End"
+         << Form(" R:%.2fs C:%.2fs", timer.RealTime(),timer.CpuTime()) << endl;
+//  Close input file
     fluka_closeinp(lunin);
-    
+//  Finish geometry    
     FinishGeometry();
-    
-    if (fVerbosityLevel >=3)
-       cout << "<== TFluka::Init() called." << endl;
-    
-    if (fVerbosityLevel >=3)
-       cout << "<== TFluka::BuildPhysics() called." << endl;
 }  
 
 //______________________________________________________________________________ 
@@ -303,18 +338,18 @@ void TFluka::ProcessEvent() {
 // Process one event
 //
     if (fStopRun) {
-       Warning("ProcessEvent", "User Run Abortion: No more events handled !\n");
-       fNEvent += 1;
-       return;
+        Warning("ProcessEvent", "User Run Abortion: No more events handled !\n");
+        fNEvent += 1;
+        return;
     }
 
     if (fVerbosityLevel >=3)
-       cout << "==> TFluka::ProcessEvent() called." << endl;
+        cout << "==> TFluka::ProcessEvent() called." << endl;
     fApplication->GeneratePrimaries();
     SOURCM.lsouit = true;
     flukam(1);
     if (fVerbosityLevel >=3)
-       cout << "<== TFluka::ProcessEvent() called." << endl;
+        cout << "<== TFluka::ProcessEvent() called." << endl;
     //
     // Increase event number
     //
@@ -326,10 +361,10 @@ Bool_t TFluka::ProcessRun(Int_t nevent) {
 //
 // Run steering
 //
-
+    
   if (fVerbosityLevel >=3)
     cout << "==> TFluka::ProcessRun(" << nevent << ") called." 
-        << endl;
+         << endl;
 
   if (fVerbosityLevel >=2) {
     cout << "\t* GLOBAL.fdrtr = " << (GLOBAL.lfdrtr?'T':'F') << endl;
@@ -338,16 +373,23 @@ Bool_t TFluka::ProcessRun(Int_t nevent) {
 
   Int_t todo = TMath::Abs(nevent);
   for (Int_t ev = 0; ev < todo; ev++) {
+      TStopwatch timer;
+      timer.Start();
       fApplication->BeginEvent();
       ProcessEvent();
       fApplication->FinishEvent();
+      cout << "Event: "<< ev
+           << Form(" R:%.2fs C:%.2fs", timer.RealTime(),timer.CpuTime()) << endl;
   }
 
   if (fVerbosityLevel >=3)
     cout << "<== TFluka::ProcessRun(" << nevent << ") called." 
-        << endl;
+         << endl;
+  
   // Write fluka specific scoring output
+  genout();
   newplo();
+  flkend();
   
   return kTRUE;
 }
@@ -358,8 +400,8 @@ Bool_t TFluka::ProcessRun(Int_t nevent) {
 // functions from GCONS 
 //____________________________________________________________________________ 
 void TFluka::Gfmate(Int_t imat, char *name, Float_t &a, Float_t &z,  
-                   Float_t &dens, Float_t &radl, Float_t &absl,
-                   Float_t* /*ubuf*/, Int_t& /*nbuf*/) {
+                    Float_t &dens, Float_t &radl, Float_t &absl,
+                    Float_t* /*ubuf*/, Int_t& /*nbuf*/) {
 //
    TGeoMaterial *mat;
    TIter next (gGeoManager->GetListOfMaterials());
@@ -380,8 +422,8 @@ void TFluka::Gfmate(Int_t imat, char *name, Float_t &a, Float_t &z,
 
 //______________________________________________________________________________ 
 void TFluka::Gfmate(Int_t imat, char *name, Double_t &a, Double_t &z,  
-                   Double_t &dens, Double_t &radl, Double_t &absl,
-                   Double_t* /*ubuf*/, Int_t& /*nbuf*/) {
+                    Double_t &dens, Double_t &radl, Double_t &absl,
+                    Double_t* /*ubuf*/, Int_t& /*nbuf*/) {
 //
    TGeoMaterial *mat;
    TIter next (gGeoManager->GetListOfMaterials());
@@ -403,8 +445,8 @@ void TFluka::Gfmate(Int_t imat, char *name, Double_t &a, Double_t &z,
 // detector composition
 //______________________________________________________________________________ 
 void TFluka::Material(Int_t& kmat, const char* name, Double_t a, 
-                     Double_t z, Double_t dens, Double_t radl, Double_t absl,
-                     Float_t* buf, Int_t nwbuf) {
+                      Double_t z, Double_t dens, Double_t radl, Double_t absl,
+                      Float_t* buf, Int_t nwbuf) {
 //
    Double_t* dbuf = fGeom->CreateDoubleArray(buf, nwbuf);  
    Material(kmat, name, a, z, dens, radl, absl, dbuf, nwbuf);
@@ -413,8 +455,8 @@ void TFluka::Material(Int_t& kmat, const char* name, Double_t a,
 
 //______________________________________________________________________________ 
 void TFluka::Material(Int_t& kmat, const char* name, Double_t a, 
-                     Double_t z, Double_t dens, Double_t radl, Double_t absl,
-                     Double_t* /*buf*/, Int_t /*nwbuf*/) {
+                      Double_t z, Double_t dens, Double_t radl, Double_t absl,
+                      Double_t* /*buf*/, Int_t /*nwbuf*/) {
 //
 // Define a material
   TGeoMaterial *mat;
@@ -432,7 +474,7 @@ void TFluka::Material(Int_t& kmat, const char* name, Double_t a,
 
 //______________________________________________________________________________ 
 void TFluka::Mixture(Int_t& kmat, const char *name, Float_t *a, 
-                    Float_t *z, Double_t dens, Int_t nlmat, Float_t *wmat) {
+                     Float_t *z, Double_t dens, Int_t nlmat, Float_t *wmat) {
 //
 // Define a material mixture
 //
@@ -452,7 +494,7 @@ void TFluka::Mixture(Int_t& kmat, const char *name, Float_t *a,
 
 //______________________________________________________________________________ 
 void TFluka::Mixture(Int_t& kmat, const char *name, Double_t *a, 
-                    Double_t *z, Double_t dens, Int_t nlmat, Double_t *wmat) {
+                     Double_t *z, Double_t dens, Int_t nlmat, Double_t *wmat) {
 //
   // Defines mixture OR COMPOUND IMAT as composed by 
   // THE BASIC NLMAT materials defined by arrays A,Z and WMAT
@@ -561,38 +603,38 @@ void TFluka::Mixture(Int_t& kmat, const char *name, Double_t *a,
      delete [] wmatnew;
      return;     
    }
-   gGeoManager->Mixture(name, a, z, dens, nlmat, wmat, kmat);
+  gGeoManager->Mixture(name, a, z, dens, nlmat, wmat, kmat);
 } 
 
 //______________________________________________________________________________ 
 void TFluka::Medium(Int_t& kmed, const char *name, Int_t nmat, 
-                   Int_t isvol, Int_t ifield, Double_t fieldm, Double_t tmaxfd, 
-                   Double_t stemax, Double_t deemax, Double_t epsil, 
-                   Double_t stmin, Float_t* ubuf, Int_t nbuf) { 
+                    Int_t isvol, Int_t ifield, Double_t fieldm, Double_t tmaxfd,
+                    Double_t stemax, Double_t deemax, Double_t epsil,
+                    Double_t stmin, Float_t* ubuf, Int_t nbuf) {
   // Define a medium
   // 
   kmed = gGeoManager->GetListOfMedia()->GetSize()+1;
   fMCGeo->Medium(kmed, name, nmat, isvol, ifield, fieldm, tmaxfd, stemax, deemax, 
-            epsil, stmin, ubuf, nbuf);
+             epsil, stmin, ubuf, nbuf);
 } 
 
 //______________________________________________________________________________ 
 void TFluka::Medium(Int_t& kmed, const char *name, Int_t nmat, 
-                   Int_t isvol, Int_t ifield, Double_t fieldm, Double_t tmaxfd, 
-                   Double_t stemax, Double_t deemax, Double_t epsil, 
-                   Double_t stmin, Double_t* ubuf, Int_t nbuf) { 
+                    Int_t isvol, Int_t ifield, Double_t fieldm, Double_t tmaxfd,
+                    Double_t stemax, Double_t deemax, Double_t epsil,
+                    Double_t stmin, Double_t* ubuf, Int_t nbuf) {
   // Define a medium
   // 
   kmed = gGeoManager->GetListOfMedia()->GetSize()+1;
   fMCGeo->Medium(kmed, name, nmat, isvol, ifield, fieldm, tmaxfd, stemax, deemax, 
-            epsil, stmin, ubuf, nbuf);
+             epsil, stmin, ubuf, nbuf);
 } 
 
 //______________________________________________________________________________ 
 void TFluka::Matrix(Int_t& krot, Double_t thetaX, Double_t phiX, 
-                   Double_t thetaY, Double_t phiY, Double_t thetaZ, 
-                   Double_t phiZ) {
-//                  
+                    Double_t thetaY, Double_t phiY, Double_t thetaZ,
+                    Double_t phiZ) {
+//        
   krot = gGeoManager->GetListOfMatrices()->GetEntriesFast();
   fMCGeo->Matrix(krot, thetaX, phiX, thetaY, phiY, thetaZ, phiZ); 
 } 
@@ -603,6 +645,8 @@ void TFluka::Gstpar(Int_t itmed, const char* param, Double_t parval) {
 //
 //
    Bool_t process = kFALSE;
+   Bool_t modelp  = kFALSE;
+   
    if (strncmp(param, "DCAY",  4) == 0 ||
        strncmp(param, "PAIR",  4) == 0 ||
        strncmp(param, "COMP",  4) == 0 ||
@@ -616,16 +660,30 @@ void TFluka::Gstpar(Int_t itmed, const char* param, Double_t parval) {
        strncmp(param, "HADR",  4) == 0 ||
        strncmp(param, "LOSS",  4) == 0 ||
        strncmp(param, "MULS",  4) == 0 ||
-       strncmp(param, "RAYL",  4) == 0) 
+       strncmp(param, "RAYL",  4) == 0 ||
+       strncmp(param, "STRA",  4) == 0) 
    {
        process = kTRUE;
    } 
    
+   if (strncmp(param, "PRIMIO_N",  8) == 0 ||
+       strncmp(param, "PRIMIO_E",  8) == 0)
+   {
+       modelp = kTRUE;
+   }
+   
    if (process) {
+       // Process switch
        SetProcess(param, Int_t (parval), itmed);
+   } else if (modelp) {
+       // Model parameters
+       SetModelParameter(param, parval, itmed);
    } else {
+       // Cuts
        SetCut(param, parval, itmed);
    }
+   
+   
 }    
 
 // functions from GGEOM 
@@ -642,42 +700,42 @@ void TFluka::Gsatt(const char *name, const char *att, Int_t val)
 
 //______________________________________________________________________________ 
 Int_t TFluka::Gsvolu(const char *name, const char *shape, Int_t nmed,  
-                    Float_t *upar, Int_t np)  {
+                     Float_t *upar, Int_t np)  {
 //
     return fMCGeo->Gsvolu(name, shape, nmed, upar, np); 
 }
 
 //______________________________________________________________________________ 
 Int_t TFluka::Gsvolu(const char *name, const char *shape, Int_t nmed,  
-                    Double_t *upar, Int_t np)  {
+                     Double_t *upar, Int_t np)  {
 //
     return fMCGeo->Gsvolu(name, shape, nmed, upar, np); 
 }
  
 //______________________________________________________________________________ 
 void TFluka::Gsdvn(const char *name, const char *mother, Int_t ndiv, 
-                  Int_t iaxis) {
+                   Int_t iaxis) {
 //
     fMCGeo->Gsdvn(name, mother, ndiv, iaxis); 
 } 
 
 //______________________________________________________________________________ 
 void TFluka::Gsdvn2(const char *name, const char *mother, Int_t ndiv, 
-                   Int_t iaxis, Double_t c0i, Int_t numed) {
+                    Int_t iaxis, Double_t c0i, Int_t numed) {
 //
     fMCGeo->Gsdvn2(name, mother, ndiv, iaxis, c0i, numed); 
 } 
 
 //______________________________________________________________________________ 
 void TFluka::Gsdvt(const char *name, const char *mother, Double_t step, 
-                  Int_t iaxis, Int_t numed, Int_t ndvmx) {
-//     
+                   Int_t iaxis, Int_t numed, Int_t ndvmx) {
+//        
     fMCGeo->Gsdvt(name, mother, step, iaxis, numed, ndvmx); 
 } 
 
 //______________________________________________________________________________ 
 void TFluka::Gsdvt2(const char *name, const char *mother, Double_t step, 
-                   Int_t iaxis, Double_t c0, Int_t numed, Int_t ndvmx) { 
+                    Int_t iaxis, Double_t c0, Int_t numed, Int_t ndvmx) {
 //
     fMCGeo->Gsdvt2(name, mother, step, iaxis, c0, numed, ndvmx); 
 } 
@@ -690,24 +748,24 @@ void TFluka::Gsord(const char * /*name*/, Int_t /*iax*/) {
 
 //______________________________________________________________________________ 
 void TFluka::Gspos(const char *name, Int_t nr, const char *mother,  
-                  Double_t x, Double_t y, Double_t z, Int_t irot, 
-                  const char *konly) {
+                   Double_t x, Double_t y, Double_t z, Int_t irot,
+                   const char *konly) {
 //
   fMCGeo->Gspos(name, nr, mother, x, y, z, irot, konly); 
 } 
 
 //______________________________________________________________________________ 
 void TFluka::Gsposp(const char *name, Int_t nr, const char *mother,  
-                   Double_t x, Double_t y, Double_t z, Int_t irot,
-                   const char *konly, Float_t *upar, Int_t np)  {
+                    Double_t x, Double_t y, Double_t z, Int_t irot,
+                    const char *konly, Float_t *upar, Int_t np)  {
   //
   fMCGeo->Gsposp(name, nr, mother, x, y, z, irot, konly, upar, np); 
 } 
 
 //______________________________________________________________________________ 
 void TFluka::Gsposp(const char *name, Int_t nr, const char *mother,  
-                   Double_t x, Double_t y, Double_t z, Int_t irot,
-                   const char *konly, Double_t *upar, Int_t np)  {
+                    Double_t x, Double_t y, Double_t z, Int_t irot,
+                    const char *konly, Double_t *upar, Int_t np)  {
   //
   fMCGeo->Gsposp(name, nr, mother, x, y, z, irot, konly, upar, np); 
 } 
@@ -822,7 +880,7 @@ Bool_t TFluka::GetMedium(const TString &volumeName,TString &name,
 
 //______________________________________________________________________________ 
 void TFluka::SetCerenkov(Int_t itmed, Int_t npckov, Float_t* ppckov,
-                        Float_t* absco, Float_t* effic, Float_t* rindex) {
+                         Float_t* absco, Float_t* effic, Float_t* rindex) {
 //
 // Set Cerenkov properties for medium itmed
 //
@@ -835,7 +893,8 @@ void TFluka::SetCerenkov(Int_t itmed, Int_t npckov, Float_t* ppckov,
 //
 //  
 //  Create object holding Cerenkov properties
-//  
+// 
+    
     TFlukaCerenkov* cerenkovProperties = new TFlukaCerenkov(npckov, ppckov, absco, effic, rindex);
 //
 //  Pass object to medium
@@ -844,7 +903,7 @@ void TFluka::SetCerenkov(Int_t itmed, Int_t npckov, Float_t* ppckov,
 }  
 
 void TFluka::SetCerenkov(Int_t itmed, Int_t npckov, Float_t* ppckov,
-                        Float_t* absco, Float_t* effic, Float_t* rindex, Float_t* rfl) {
+                         Float_t* absco, Float_t* effic, Float_t* rindex, Float_t* rfl) {
 //
 // Set Cerenkov properties for medium itmed
 //
@@ -867,16 +926,61 @@ void TFluka::SetCerenkov(Int_t itmed, Int_t npckov, Float_t* ppckov,
 
 
 //______________________________________________________________________________ 
-void TFluka::SetCerenkov(Int_t /*itmed*/, Int_t /*npckov*/, Double_t * /*ppckov*/,
-                        Double_t * /*absco*/, Double_t * /*effic*/, Double_t * /*rindex*/) {
+void TFluka::SetCerenkov(Int_t itmed, Int_t npckov, Double_t *ppckov,
+                         Double_t *absco, Double_t *effic, Double_t *rindex) {
+//
+// Set Cerenkov properties for medium itmed
+//
+// npckov: number of sampling points
+// ppckov: energy values
+// absco:  absorption length
+// effic:  quantum efficiency
+// rindex: refraction index
+//
+
 //
-//  Double_t version not implemented
+//  Double_t version 
+  Float_t* fppckov = CreateFloatArray(ppckov, npckov);
+  Float_t* fabsco  = CreateFloatArray(absco,  npckov);
+  Float_t* feffic  = CreateFloatArray(effic,  npckov);
+  Float_t* frindex = CreateFloatArray(rindex, npckov);
+
+  SetCerenkov(itmed, npckov, fppckov, fabsco, feffic, frindex);
+
+  delete [] fppckov;
+  delete [] fabsco;
+  delete [] feffic;
+  delete [] frindex;
 }  
 
-void TFluka::SetCerenkov(Int_t /*itmed*/, Int_t /*npckov*/, Double_t* /*ppckov*/,
-                        Double_t* /*absco*/, Double_t* /*effic*/, Double_t* /*rindex*/, Double_t* /*rfl*/) { 
+void TFluka::SetCerenkov(Int_t itmed, Int_t npckov, Double_t* ppckov,
+                         Double_t* absco, Double_t* effic, Double_t* rindex, Double_t* rfl) {
 //
-// //  Double_t version not implemented
+// Set Cerenkov properties for medium itmed
+//
+// npckov: number of sampling points
+// ppckov: energy values
+// absco:  absorption length
+// effic:  quantum efficiency
+// rindex: refraction index
+// rfl:    reflectivity for boundary to medium itmed
+//
+
+//
+// //  Double_t version 
+  Float_t* fppckov = CreateFloatArray(ppckov, npckov);
+  Float_t* fabsco  = CreateFloatArray(absco,  npckov);
+  Float_t* feffic  = CreateFloatArray(effic,  npckov);
+  Float_t* frindex = CreateFloatArray(rindex, npckov);
+  Float_t* frfl    = CreateFloatArray(rfl,    npckov);
+
+  SetCerenkov(itmed, npckov, fppckov, fabsco, feffic, frindex, frfl);
+
+  delete [] fppckov;
+  delete [] fabsco;
+  delete [] feffic;
+  delete [] frindex;
+  delete [] frfl;
 }
 
 // Euclid
@@ -898,7 +1002,11 @@ Int_t TFluka::GetMedium() const {
 //
 //  Get the medium number for the current fluka region
 //
-    return fGeom->GetMedium(); // this I need to check due to remapping !!!
+    if (gGeoManager->IsOutside()) {
+       return (-1);
+    } else {
+       return (fGeom->GetMedium()); // this I need to check due to remapping !!!
+    }
 }
 
 //____________________________________________________________________________ 
@@ -921,11 +1029,24 @@ Int_t TFluka::GetDummyLattice() const
 //_____________________________________________________________________________
 Int_t TFluka::IdFromPDG(Int_t pdg) const 
 {
+
     //
     // Return Fluka code from PDG and pseudo ENDF code
-    
+    Int_t idSpecial[4] = {TFlukaIon::GetIonPdg(2,4), 
+                         TFlukaIon::GetIonPdg(2,3), 
+                         TFlukaIon::GetIonPdg(1,3), 
+                         TFlukaIon::GetIonPdg(1,2)};    
     // Catch the feedback photons
     if (pdg == 50000051) return (kFLUKAoptical);
+
+    // Light ions (d,t,h3,alpha)
+    for (Int_t i = 0; i < 4; i++) {
+       if (pdg == idSpecial[i]) return (i + kFLUKAcodemin);
+    }
+    
+    // Heavy ions
+    if (pdg > TFlukaIon::GetIonPdg(1,1)) return (-2);
+
     // MCIHAD() goes from pdg to fluka internal.
     Int_t intfluka = mcihad(pdg);
     // KPTOIP array goes from internal to official
@@ -937,40 +1058,44 @@ Int_t TFluka::PDGFromId(Int_t id) const
 {
   //
   // Return PDG code and pseudo ENDF code from Fluka code
-  //                      Alpha     He3       Triton    Deuteron  gen. ion  opt. photon   
-    Int_t idSpecial[6] = {10020040, 10020030, 10010030, 10010020, 10000000, 50000050};
+    Int_t idSpecial[6] = {TFlukaIon::GetIonPdg(2,4), // alpha 
+                         TFlukaIon::GetIonPdg(2,3), // He3
+                         TFlukaIon::GetIonPdg(1,3), // triton
+                         TFlukaIon::GetIonPdg(1,2), // deuteron 
+                         TFlukaIon::GetIonPdg(0,0), // gen. ion 
+                         50000050};
   // IPTOKP array goes from official to internal
 
     if (id == kFLUKAoptical) {
 // Cerenkov photon
-       if (fVerbosityLevel >= 3)
-           printf("\n PDGFromId: Cerenkov Photon \n");
-       return  50000050;
+//        if (fVerbosityLevel >= 3)
+//            printf("\n PDGFromId: Cerenkov Photon \n");
+        return  50000050;
     }
 // Error id    
     if (id == 0 || id < kFLUKAcodemin || id > kFLUKAcodemax) {
-       if (fVerbosityLevel >= 3)
-           printf("PDGFromId: Error id = 0\n");
-       return -1;
+        if (fVerbosityLevel >= 3)
+            printf("PDGFromId: Error id = 0 %5d %5d\n", id, fCaller);
+        return -1;
     }
 // Good id    
     if (id > 0) {
-       Int_t intfluka = GetFlukaIPTOKP(id);
-       if (intfluka == 0) {
-           if (fVerbosityLevel >= 3)
-               printf("PDGFromId: Error intfluka = 0: %d\n", id);
-           return -1;
-       } else if (intfluka < 0) {
-           if (fVerbosityLevel >= 3)
-               printf("PDGFromId: Error intfluka < 0: %d\n", id);
-           return -1;
-       }
-       if (fVerbosityLevel >= 3)
-           printf("mpdgha called with %d %d \n", id, intfluka);
-       return mpdgha(intfluka);
+        Int_t intfluka = GetFlukaIPTOKP(id);
+        if (intfluka == 0) {
+            if (fVerbosityLevel >= 3)
+                printf("PDGFromId: Error intfluka = 0: %d\n", id);
+            return -1;
+        } else if (intfluka < 0) {
+            if (fVerbosityLevel >= 3)
+                printf("PDGFromId: Error intfluka < 0: %d\n", id);
+            return -1;
+        }
+//        if (fVerbosityLevel >= 3)
+//            printf("mpdgha called with %d %d \n", id, intfluka);
+        return mpdgha(intfluka);
     } else {
-       // ions and optical photons
-       return idSpecial[id - kFLUKAcodemin];
+        // ions and optical photons
+        return idSpecial[id - kFLUKAcodemin];
     }
 }
 
@@ -999,10 +1124,10 @@ void TFluka::SetProcess(const char* flagName, Int_t flagValue, Int_t imed)
     TFlukaConfigOption* proc;
     while((proc = (TFlukaConfigOption*)next()))
     { 
-       if (proc->Medium() == imed) {
-           proc->SetProcess(flagName, flagValue);
-           return;
-       }
+        if (proc->Medium() == imed) {
+            proc->SetProcess(flagName, flagValue);
+            return;
+        }
     }
     proc = new TFlukaConfigOption(imed);
     proc->SetProcess(flagName, flagValue);
@@ -1028,10 +1153,10 @@ void TFluka::SetCut(const char* cutName, Double_t cutValue, Int_t imed)
     TFlukaConfigOption* proc;
     while((proc = (TFlukaConfigOption*)next()))
     { 
-       if (proc->Medium() == imed) {
-           proc->SetCut(cutName, cutValue);
-           return;
-       }
+        if (proc->Medium() == imed) {
+            proc->SetCut(cutName, cutValue);
+            return;
+        }
     }
 
     proc = new TFlukaConfigOption(imed);
@@ -1039,6 +1164,27 @@ void TFluka::SetCut(const char* cutName, Double_t cutValue, Int_t imed)
     fUserConfig->Add(proc);
 }
 
+
+//______________________________________________________________________________ 
+void TFluka::SetModelParameter(const char* parName, Double_t parValue, Int_t imed)
+{
+// Set model parameter for material imed
+//
+    TIter next(fUserConfig);
+    TFlukaConfigOption* proc;
+    while((proc = (TFlukaConfigOption*)next()))
+    { 
+        if (proc->Medium() == imed) {
+            proc->SetModelParameter(parName, parValue);
+            return;
+        }
+    }
+
+    proc = new TFlukaConfigOption(imed);
+    proc->SetModelParameter(parName, parValue);
+    fUserConfig->Add(proc);
+}
+
 //______________________________________________________________________________ 
 Bool_t TFluka::SetCut(const char* cutName, Double_t cutValue)
 {
@@ -1050,21 +1196,22 @@ Bool_t TFluka::SetCut(const char* cutName, Double_t cutValue)
 }
 
 
-void TFluka::SetUserScoring(const char* option, Int_t npr, char* outfile, Float_t* what)
+void TFluka::SetUserScoring(const char* option, const char* sdum, Int_t npr, char* outfile, Float_t* what)
 {
 //
 // Adds a user scoring option to the list
 //
-    TFlukaScoringOption* opt = new TFlukaScoringOption(option, "User Scoring", npr,outfile,what);
+    TFlukaScoringOption* opt = new TFlukaScoringOption(option, sdum, npr,outfile,what);
     fUserScore->Add(opt);
 }
 //______________________________________________________________________________
-void TFluka::SetUserScoring(const char* option, Int_t npr, char* outfile, Float_t* what, const char* det1, const char* det2, const char* det3)
+void TFluka::SetUserScoring(const char* option, const char* sdum, Int_t npr, char* outfile, Float_t* what, 
+                           const char* det1, const char* det2, const char* det3)
 {
 //
 // Adds a user scoring option to the list
 //
-    TFlukaScoringOption* opt = new TFlukaScoringOption(option, "User Scoring", npr, outfile, what, det1, det2, det3);
+    TFlukaScoringOption* opt = new TFlukaScoringOption(option, sdum, npr, outfile, what, det1, det2, det3);
     fUserScore->Add(opt);
 }
 
@@ -1083,24 +1230,22 @@ void TFluka::InitPhysics()
 //
 // Construct file names
     FILE *pFlukaVmcCoreInp, *pFlukaVmcFlukaMat, *pFlukaVmcInp;
-    TString sFlukaVmcCoreInp = getenv("ALICE_ROOT");
-    sFlukaVmcCoreInp +="/TFluka/input/";
     TString sFlukaVmcTmp = "flukaMat.inp";
     TString sFlukaVmcInp = GetInputFileName();
-    sFlukaVmcCoreInp += GetCoreInputFileName();
+    TString sFlukaVmcCoreInp = GetCoreInputFileName();
     
 // Open files 
     if ((pFlukaVmcCoreInp = fopen(sFlukaVmcCoreInp.Data(),"r")) == NULL) {
-       Warning("InitPhysics", "\nCannot open file %s\n",sFlukaVmcCoreInp.Data());
-       exit(1);
+        Warning("InitPhysics", "\nCannot open file %s\n",sFlukaVmcCoreInp.Data());
+        exit(1);
     }
     if ((pFlukaVmcFlukaMat = fopen(sFlukaVmcTmp.Data(),"r")) == NULL) {
-       Warning("InitPhysics", "\nCannot open file %s\n",sFlukaVmcTmp.Data());
-       exit(1);
+        Warning("InitPhysics", "\nCannot open file %s\n",sFlukaVmcTmp.Data());
+        exit(1);
     }
     if ((pFlukaVmcInp = fopen(sFlukaVmcInp.Data(),"w")) == NULL) {
-       Warning("InitPhysics", "\nCannot open file %s\n",sFlukaVmcInp.Data());
-       exit(1);
+        Warning("InitPhysics", "\nCannot open file %s\n",sFlukaVmcInp.Data());
+        exit(1);
     }
 
 // Copy core input file 
@@ -1108,27 +1253,27 @@ void TFluka::InitPhysics()
     Float_t fEventsPerRun;
     
     while ((fgets(sLine,255,pFlukaVmcCoreInp)) != NULL) {
-       if (strncmp(sLine,"GEOEND",6) != 0)
-           fprintf(pFlukaVmcInp,"%s",sLine); // copy until GEOEND card
-       else {
-           fprintf(pFlukaVmcInp,"GEOEND\n");   // add GEOEND card
-           goto flukamat;
-       }
+        if (strncmp(sLine,"GEOEND",6) != 0)
+            fprintf(pFlukaVmcInp,"%s",sLine); // copy until GEOEND card
+        else {
+            fprintf(pFlukaVmcInp,"GEOEND\n");   // add GEOEND card
+            goto flukamat;
+        }
     } // end of while until GEOEND card
     
 
  flukamat:
     while ((fgets(sLine,255,pFlukaVmcFlukaMat)) != NULL) { // copy flukaMat.inp file
-       fprintf(pFlukaVmcInp,"%s\n",sLine);
+        fprintf(pFlukaVmcInp,"%s\n",sLine);
     }
     
     while ((fgets(sLine,255,pFlukaVmcCoreInp)) != NULL) { 
-       if (strncmp(sLine,"START",5) != 0)
-           fprintf(pFlukaVmcInp,"%s\n",sLine);
-       else {
-           sscanf(sLine+10,"%10f",&fEventsPerRun);
-           goto fin;
-       }
+        if (strncmp(sLine,"START",5) != 0)
+            fprintf(pFlukaVmcInp,"%s\n",sLine);
+        else {
+            sscanf(sLine+10,"%10f",&fEventsPerRun);
+            goto fin;
+        }
     } //end of while until START card
     
  fin:
@@ -1146,7 +1291,7 @@ void TFluka::InitPhysics()
 // Process Fluka specific scoring options
 //
     TFlukaScoringOption::SetStaticInfo(pFlukaVmcInp, fGeom);
-    Float_t loginp        = 49.0;
+    Float_t loginp        = -49.0;
     Int_t inp             = 0;
     Int_t nscore          = fUserScore->GetEntries();
     
@@ -1155,34 +1300,38 @@ void TFluka::InitPhysics()
 
     for (Int_t isc = 0; isc < nscore; isc++) 
     {
-       mopo = dynamic_cast<TFlukaScoringOption*> (fUserScore->At(isc));
-       char*    fileName = mopo->GetFileName();
-       Int_t    size     = strlen(fileName);
-       Float_t  lun      = -1.;
+        mopo = dynamic_cast<TFlukaScoringOption*> (fUserScore->At(isc));
+        char*    fileName = mopo->GetFileName();
+        Int_t    size     = strlen(fileName);
+        Float_t  lun      = -1.;
 //
 // Check if new output file has to be opened
-       for (Int_t isci = 0; isci < isc; isci++) {
-
-           
-           mopi = dynamic_cast<TFlukaScoringOption*> (fUserScore->At(isci));
-           if(strncmp(mopi->GetFileName(), fileName, size)==0) {
-               // 
-               // No, the file already exists
-               lun = mopi->GetLun();
-               mopo->SetLun(lun);
-               break;
-           }
-       } // inner loop
-
-       if (lun == -1.) {
-           // Open new output file
-           inp++;
-           mopo->SetLun(loginp + inp);
-           mopo->WriteOpenFlukaFile();
-       }
-       mopo->WriteFlukaInputCards();
+        for (Int_t isci = 0; isci < isc; isci++) {
+
+        
+            mopi = dynamic_cast<TFlukaScoringOption*> (fUserScore->At(isci));
+            if(strncmp(mopi->GetFileName(), fileName, size)==0) {
+                //
+                // No, the file already exists
+                lun = mopi->GetLun();
+                mopo->SetLun(lun);
+                break;
+            }
+        } // inner loop
+
+        if (lun == -1.) {
+            // Open new output file
+            inp++;
+            mopo->SetLun(loginp + inp);
+            mopo->WriteOpenFlukaFile();
+        }
+        mopo->WriteFlukaInputCards();
     }
-    
+
+// Add RANDOMIZ card
+    fprintf(pFlukaVmcInp,"RANDOMIZ  %10.1f%10.0f\n", 1., Float_t(gRandom->GetSeed()));
+// User defined ion
+    if (fUserIons) TFlukaIon::WriteUserInputCard(pFlukaVmcInp);
 // Add START and STOP card
     fprintf(pFlukaVmcInp,"START     %10.1f\n",fEventsPerRun);
     fprintf(pFlukaVmcInp,"STOP      \n");
@@ -1198,13 +1347,13 @@ void TFluka::InitPhysics()
 // Initialisation needed for Cerenkov photon production and transport
     TObjArray *matList = GetFlukaMaterials();
     Int_t nmaterial =  matList->GetEntriesFast();
-    fMaterials = new Int_t[nmaterial+3];
+    fMaterials = new Int_t[nmaterial+25];
     
     for (Int_t im = 0; im < nmaterial; im++)
     {
-       TGeoMaterial* material = dynamic_cast<TGeoMaterial*> (matList->At(im));
-       Int_t idmat = material->GetIndex();
-       fMaterials[idmat] = im;
+        TGeoMaterial* material = dynamic_cast<TGeoMaterial*> (matList->At(im));
+        Int_t idmat = material->GetIndex();
+        fMaterials[idmat] = im;
     }
 } // end of InitPhysics
 
@@ -1213,10 +1362,13 @@ void TFluka::InitPhysics()
 void TFluka::SetMaxStep(Double_t step)
 {
 // Set the maximum step size
-    if (step > 1.e4) return;
+//    if (step > 1.e4) return;
     
-    Int_t mreg, latt;
-    fGeom->GetCurrentRegion(mreg, latt);
+//    Int_t mreg=0, latt=0;
+//    fGeom->GetCurrentRegion(mreg, latt);
+
+    
+    Int_t mreg = fGeom->GetCurrentRegion();
     STEPSZ.stepmx[mreg - 1] = step;
 }
 
@@ -1261,30 +1413,42 @@ void TFluka::TrackPosition(TLorentzVector& position) const
   if (caller == kENDRAW    || caller == kUSDRAW || 
       caller == kBXExiting || caller == kBXEntering || 
       caller == kUSTCKV) { 
-    position.SetX(GetXsco());
-    position.SetY(GetYsco());
-    position.SetZ(GetZsco());
-    position.SetT(TRACKR.atrack);
+      position.SetX(GetXsco());
+      position.SetY(GetYsco());
+      position.SetZ(GetZsco());
+      position.SetT(TRACKR.atrack);
   }
-  else if (caller == kMGDRAW) { 
-    position.SetX(TRACKR.xtrack[TRACKR.ntrack]);
-    position.SetY(TRACKR.ytrack[TRACKR.ntrack]);
-    position.SetZ(TRACKR.ztrack[TRACKR.ntrack]);
-    position.SetT(TRACKR.atrack);
+  else if (caller == kMGDRAW) {
+      Int_t i = -1;
+      if ((i = fPrimaryElectronIndex) > -1) {
+         // Primary Electron Ionisation
+         Double_t x, y, z, t;
+         GetPrimaryElectronPosition(i, x, y, z, t);
+         position.SetX(x);
+         position.SetY(y);
+         position.SetZ(z);
+         position.SetT(t);
+      } else {
+         position.SetX(TRACKR.xtrack[TRACKR.ntrack]);
+         position.SetY(TRACKR.ytrack[TRACKR.ntrack]);
+         position.SetZ(TRACKR.ztrack[TRACKR.ntrack]);
+         position.SetT(TRACKR.atrack);
+      }
   }
   else if (caller == kSODRAW) { 
-    position.SetX(TRACKR.xtrack[TRACKR.ntrack]);
-    position.SetY(TRACKR.ytrack[TRACKR.ntrack]);
-    position.SetZ(TRACKR.ztrack[TRACKR.ntrack]);
-    position.SetT(0);
+      Int_t ist = FLKSTK.npflka;
+      position.SetX(FLKSTK.xflk[ist]);
+      position.SetY(FLKSTK.yflk[ist]);
+      position.SetZ(FLKSTK.zflk[ist]);
+      position.SetT(FLKSTK.agestk[ist]);
   } else if (caller == kMGResumedTrack) { 
-    position.SetX(TRACKR.spausr[0]);
-    position.SetY(TRACKR.spausr[1]);
-    position.SetZ(TRACKR.spausr[2]);
-    position.SetT(TRACKR.spausr[3]);
+      position.SetX(TRACKR.spausr[0]);
+      position.SetY(TRACKR.spausr[1]);
+      position.SetZ(TRACKR.spausr[2]);
+      position.SetT(TRACKR.spausr[3]);
   }
   else
-    Warning("TrackPosition","position not available");
+      Warning("TrackPosition","position not available");
 }
 
 //______________________________________________________________________________ 
@@ -1300,22 +1464,34 @@ void TFluka::TrackPosition(Double_t& x, Double_t& y, Double_t& z) const
   if (caller == kENDRAW    || caller == kUSDRAW || 
       caller == kBXExiting || caller == kBXEntering || 
       caller == kUSTCKV) { 
-    x = GetXsco();
-    y = GetYsco();
-    z = GetZsco();
+      x = GetXsco();
+      y = GetYsco();
+      z = GetZsco();
+  }
+  else if (caller == kMGDRAW) { 
+      Int_t i = -1;
+      if ((i = fPrimaryElectronIndex) > -1) {
+         Double_t t;
+         GetPrimaryElectronPosition(i, x, y, z, t);
+      } else {
+         x = TRACKR.xtrack[TRACKR.ntrack];
+         y = TRACKR.ytrack[TRACKR.ntrack];
+         z = TRACKR.ztrack[TRACKR.ntrack];
+      }
   }
-  else if (caller == kMGDRAW || caller == kSODRAW) { 
-    x = TRACKR.xtrack[TRACKR.ntrack];
-    y = TRACKR.ytrack[TRACKR.ntrack];
-    z = TRACKR.ztrack[TRACKR.ntrack];
+  else if (caller == kSODRAW) { 
+      Int_t ist = FLKSTK.npflka;
+      x = FLKSTK.xflk[ist];
+      y = FLKSTK.yflk[ist];
+      z = FLKSTK.zflk[ist];
   }
   else if (caller == kMGResumedTrack) {
-    x = TRACKR.spausr[0];
-    y = TRACKR.spausr[1];
-    z = TRACKR.spausr[2];
+      x = TRACKR.spausr[0];
+      y = TRACKR.spausr[1];
+      z = TRACKR.spausr[2];
   }
   else
-    Warning("TrackPosition","position not available");
+      Warning("TrackPosition","position not available");
 }
 
 //______________________________________________________________________________ 
@@ -1332,34 +1508,74 @@ void TFluka::TrackMomentum(TLorentzVector& momentum) const
   FlukaCallerCode_t  caller = GetCaller();
   FlukaProcessCode_t icode  = GetIcode();
   
-  if (caller != kEEDRAW && caller != kMGResumedTrack && 
+  if (caller  != kEEDRAW         && 
+      caller  != kMGResumedTrack && 
+      caller  != kSODRAW         &&
+      caller  != kUSDRAW         &&
       (caller != kENDRAW || (icode != kEMFSCOstopping1 && icode != kEMFSCOstopping2))) {
-    if (TRACKR.ptrack >= 0) {
-      momentum.SetPx(TRACKR.ptrack*TRACKR.cxtrck);
-      momentum.SetPy(TRACKR.ptrack*TRACKR.cytrck);
-      momentum.SetPz(TRACKR.ptrack*TRACKR.cztrck);
-      momentum.SetE(TRACKR.etrack);
-      return;
-    }
-    else {
-      Double_t p = sqrt(TRACKR.etrack * TRACKR.etrack - ParticleMassFPC(TRACKR.jtrack) * ParticleMassFPC(TRACKR.jtrack));
-      momentum.SetPx(p*TRACKR.cxtrck);
-      momentum.SetPy(p*TRACKR.cytrck);
-      momentum.SetPz(p*TRACKR.cztrck);
-      momentum.SetE(TRACKR.etrack);
-      return;
-    }
+      if (TRACKR.ptrack >= 0) {
+         momentum.SetPx(TRACKR.ptrack*TRACKR.cxtrck);
+         momentum.SetPy(TRACKR.ptrack*TRACKR.cytrck);
+         momentum.SetPz(TRACKR.ptrack*TRACKR.cztrck);
+         momentum.SetE(TRACKR.etrack);
+         return;
+      }
+      else {
+         Double_t p = sqrt(TRACKR.etrack * TRACKR.etrack - ParticleMassFPC(TRACKR.jtrack) * ParticleMassFPC(TRACKR.jtrack));
+         momentum.SetPx(p*TRACKR.cxtrck);
+         momentum.SetPy(p*TRACKR.cytrck);
+         momentum.SetPz(p*TRACKR.cztrck);
+         momentum.SetE(TRACKR.etrack);
+         return;
+      }
   } else if  (caller == kMGResumedTrack) {
-    momentum.SetPx(TRACKR.spausr[4]);
-    momentum.SetPy(TRACKR.spausr[5]);
-    momentum.SetPz(TRACKR.spausr[6]);
-    momentum.SetE (TRACKR.spausr[7]);
-    return;
+      momentum.SetPx(TRACKR.spausr[4]);
+      momentum.SetPy(TRACKR.spausr[5]);
+      momentum.SetPz(TRACKR.spausr[6]);
+      momentum.SetE (TRACKR.spausr[7]);
+      return;
   } else if (caller == kENDRAW && (icode == kEMFSCOstopping1 || icode == kEMFSCOstopping2)) {
       momentum.SetPx(0.);
       momentum.SetPy(0.);
       momentum.SetPz(0.);
       momentum.SetE(TrackMass());
+      
+  } else if (caller == kSODRAW) {
+      Int_t ist  = FLKSTK.npflka;
+      Double_t p = FLKSTK.pmoflk[ist];
+      Int_t ifl  = FLKSTK.iloflk[ist];
+      Double_t m = PAPROP.am[ifl + 6];
+      Double_t e = TMath::Sqrt(p * p + m * m);
+      momentum.SetPx(p * FLKSTK.txflk[ist]);
+      momentum.SetPy(p * FLKSTK.tyflk[ist]);
+      momentum.SetPz(p * FLKSTK.tzflk[ist]);
+      momentum.SetE(e);
+  } else if (caller == kUSDRAW) {
+      if (icode == kEMFSCObrems  || 
+         icode == kEMFSCOmoller || 
+         icode == kEMFSCObhabha || 
+         icode == kEMFSCOcompton ) 
+      {
+         momentum.SetPx(fPint[0]);
+         momentum.SetPy(fPint[1]);
+         momentum.SetPz(fPint[2]);
+         momentum.SetE(fPint[3]);
+      } else if (icode == kKASKADdray  || 
+                icode == kKASKADbrems || 
+                icode == kKASKADpair) {
+         momentum.SetPx(GENSTK.plr[0] * GENSTK.cxr[0]);
+         momentum.SetPy(GENSTK.plr[0] * GENSTK.cyr[0]);
+         momentum.SetPz(GENSTK.plr[0] * GENSTK.czr[0]);
+         momentum.SetE (GENSTK.tki[0] + PAPROP.am[GENSTK.kpart[0]+6]);
+      } else {
+         Double_t p = sqrt(TRACKR.etrack * TRACKR.etrack 
+                           - ParticleMassFPC(TRACKR.jtrack) 
+                           * ParticleMassFPC(TRACKR.jtrack));
+         momentum.SetPx(p*TRACKR.cxtrck);
+         momentum.SetPy(p*TRACKR.cytrck);
+         momentum.SetPz(p*TRACKR.cztrck);
+         momentum.SetE(TRACKR.etrack);
+      }
   }
   else
     Warning("TrackMomentum","momentum not available");
@@ -1378,7 +1594,10 @@ void TFluka::TrackMomentum(Double_t& px, Double_t& py, Double_t& pz, Double_t& e
 // PAPROP.am[TRACKR.jtrack] = particle mass in gev
   FlukaCallerCode_t   caller = GetCaller();
   FlukaProcessCode_t  icode  = GetIcode();
-  if (caller != kEEDRAW && caller != kMGResumedTrack && 
+  if (caller != kEEDRAW         && 
+      caller != kMGResumedTrack && 
+      caller != kSODRAW         &&
+      caller != kUSDRAW         &&
       (caller != kENDRAW || (icode != kEMFSCOstopping1 && icode != kEMFSCOstopping2))) {
     if (TRACKR.ptrack >= 0) {
       px = TRACKR.ptrack*TRACKR.cxtrck;
@@ -1406,9 +1625,42 @@ void TFluka::TrackMomentum(Double_t& px, Double_t& py, Double_t& pz, Double_t& e
       py = 0.;
       pz = 0.;
       e  = TrackMass();
+  } else if (caller == kSODRAW) {
+      Int_t ist  = FLKSTK.npflka;
+      Double_t p = FLKSTK.pmoflk[ist];
+      Int_t ifl  = FLKSTK.iloflk[ist];
+      Double_t m = PAPROP.am[ifl + 6];
+               e = TMath::Sqrt(p * p + m * m);
+      px = p * FLKSTK.txflk[ist];
+      py = p * FLKSTK.tyflk[ist];
+      pz = p * FLKSTK.tzflk[ist];
+  } else if (caller == kUSDRAW) {
+      if (icode == kEMFSCObrems  || 
+         icode == kEMFSCOmoller || 
+         icode == kEMFSCObhabha || 
+         icode == kEMFSCOcompton ) 
+      {
+         px = fPint[0];
+         py = fPint[1];
+         pz = fPint[2];
+         e  = fPint[3];
+      } else if (icode == kKASKADdray  || 
+                icode == kKASKADbrems || 
+                icode == kKASKADpair) {
+         px = GENSTK.plr[0] * GENSTK.cxr[0];
+         py = GENSTK.plr[0] * GENSTK.cyr[0];
+         pz = GENSTK.plr[0] * GENSTK.czr[0];
+         e  = GENSTK.tki[0] + PAPROP.am[GENSTK.kpart[0]+6];
+      } else {
+         Double_t p = sqrt(TRACKR.etrack * TRACKR.etrack - ParticleMassFPC(TRACKR.jtrack) *  ParticleMassFPC(TRACKR.jtrack));
+         px = p*TRACKR.cxtrck;
+         py = p*TRACKR.cytrck;
+         pz = p*TRACKR.cztrck;
+         e  = TRACKR.etrack;
+      }
   }
   else
-    Warning("TrackMomentum","momentum not available");
+      Warning("TrackMomentum","momentum not available");
 }
 
 //______________________________________________________________________________ 
@@ -1416,17 +1668,29 @@ Double_t TFluka::TrackStep() const
 {
 // Return the length in centimeters of the current step
 // TRACKR.ctrack = total curved path
-  FlukaCallerCode_t caller = GetCaller();
-  if (caller == kBXEntering || caller == kBXExiting || 
-      caller == kENDRAW     || caller == kUSDRAW || 
-      caller == kUSTCKV     || caller == kMGResumedTrack)
-    return 0.0;
-  else if (caller == kMGDRAW)
-    return TRACKR.ctrack;
-  else {
-    Warning("TrackStep", "track step not available");
-    return 0.0;
-  }  
+    FlukaCallerCode_t caller = GetCaller();
+    if (caller == kMGDRAW) {
+       Int_t i;
+       if ((i = fPrimaryElectronIndex) > -1) {
+           if (i > 0) {
+               return (fPIlength[i] - fPIlength[i-1]); 
+           } else {
+               Double_t s (TRACKR.ctrack - (fPIlength[fNPI - 1] - fPIlength[0]));
+               return s;
+           }
+       } else {
+           return TRACKR.ctrack;
+       }
+    } else if (caller == kBXEntering || caller == kBXExiting || 
+              caller == kENDRAW     || caller == kUSDRAW || 
+              caller == kUSTCKV     || caller == kMGResumedTrack ||
+              caller == kSODRAW)
+    {
+       return 0.0;
+    } else {
+       Warning("TrackStep", "track step not available");
+       return 0.0;
+    }  
 }
 
 //______________________________________________________________________________ 
@@ -1434,30 +1698,51 @@ Double_t TFluka::TrackLength() const
 {
 // TRACKR.cmtrck = cumulative curved path since particle birth
   FlukaCallerCode_t caller = GetCaller();
-  if (caller == kBXEntering || caller == kBXExiting || 
-      caller == kENDRAW || caller == kUSDRAW || caller == kMGDRAW || 
-      caller == kUSTCKV) 
-    return TRACKR.cmtrck;
+  if (caller == kMGDRAW) {
+      Int_t i;
+      if ((i = fPrimaryElectronIndex) > -1) {
+         return fPIlength[i];
+      } else {
+         return TRACKR.cmtrck;
+      }
+      
+  } else if (caller == kBXEntering || caller == kBXExiting || 
+            caller == kENDRAW || caller == kUSDRAW || caller == kUSTCKV) 
+      return TRACKR.cmtrck;
   else if (caller == kMGResumedTrack) 
-    return TRACKR.spausr[8];
+      return TRACKR.spausr[8];
+  else if (caller == kSODRAW)
+      return 0.0;
   else {
-    Warning("TrackLength", "track length not available");
-    return 0.0;
-  } 
+      Warning("TrackLength", "track length not available for caller %5d \n", caller);
+      return 0.0;
+  }
 }
 
+
 //______________________________________________________________________________ 
 Double_t TFluka::TrackTime() const
 {
 // Return the current time of flight of the track being transported
 // TRACKR.atrack = age of the particle
   FlukaCallerCode_t caller = GetCaller();
-  if (caller == kBXEntering || caller == kBXExiting || 
-      caller == kENDRAW     || caller == kUSDRAW    || caller == kMGDRAW || 
-      caller == kUSTCKV)
+  if (caller == kMGDRAW) {
+      Int_t i;
+      if ((i = fPrimaryElectronIndex) > -1) {
+         Double_t t = fPItime[i];
+         return t;
+      } else {
+         return TRACKR.atrack;
+      }
+  } else if (caller == kBXEntering || caller == kBXExiting || 
+            caller == kENDRAW     || caller == kUSDRAW    || 
+            caller == kUSTCKV)
     return TRACKR.atrack;
   else if (caller == kMGResumedTrack)
     return TRACKR.spausr[3];
+  else if (caller == kSODRAW) {
+      return (FLKSTK.agestk[FLKSTK.npflka]);
+  }
   else {
     Warning("TrackTime", "track time not available");
     return 0.0;
@@ -1481,27 +1766,76 @@ Double_t TFluka::Edep() const
   // If coming from usdraw we just signal particle production - no edep
   // If just first time after resuming, no edep for the primary
   FlukaCallerCode_t caller = GetCaller();
+    
   if (caller == kBXExiting || caller == kBXEntering || 
-      caller == kUSDRAW    || caller == kMGResumedTrack) return 0.0;
+      caller == kUSDRAW    || caller == kMGResumedTrack ||
+      caller == kSODRAW) 
+      return 0.0;
   Double_t sum = 0;
-  for ( Int_t j=0;j<TRACKR.mtrack;j++) {
-      sum +=TRACKR.dtrack[j];  
-  }
-  if (TRACKR.ntrack == 0 && TRACKR.mtrack == 0)
-      return fRull + sum;
-  else {
+  Int_t i = -1;
+  
+  // Material with primary ionisation activated but number of primary electrons nprim = 0
+  if (fPrimaryElectronIndex == -2) return 0.0;
+  // nprim > 0
+  if ((i = fPrimaryElectronIndex) > -1) {
+      // Primary ionisation
+      sum = GetPrimaryElectronKineticEnergy(i);
+      if (sum > 100.) {
+         printf("edep > 100. %d %d %f \n", i, ALLDLT.nalldl, sum);
+      }
       return sum;
+  } else {
+      // Normal ionisation
+      if (TRACKR.mtrack > 1) printf("Edep: %6d\n", TRACKR.mtrack);
+      
+      for ( Int_t j=0;j<TRACKR.mtrack;j++) {
+         sum +=TRACKR.dtrack[j];  
+      }
+      if (TRACKR.ntrack == 0 && TRACKR.mtrack == 0)
+         return fRull + sum;
+      else {
+         return sum;
+      }
   }
 }
 
+//______________________________________________________________________________ 
+Int_t TFluka::CorrectFlukaId() const
+{
+   // since we don't put photons and e- created bellow transport cut on the vmc stack
+   // and there is a call to endraw for energy deposition for each of them
+   // and they have the track number of their parent, but different identity (pdg)
+   // so we want to assign also their parent identity.
+
+   if( (IsTrackStop())
+        && TRACKR.ispusr[mkbmx2 - 4] == TRACKR.ispusr[mkbmx2 - 1]
+        && TRACKR.jtrack != TRACKR.ispusr[mkbmx2 - 3] ) {
+      if (fVerbosityLevel >=3)
+         cout << "CorrectFlukaId() for icode=" << GetIcode()
+               << " track=" << TRACKR.ispusr[mkbmx2 - 1]
+               << " current PDG=" << PDGFromId(TRACKR.jtrack)
+               << " assign parent PDG=" << PDGFromId(TRACKR.ispusr[mkbmx2 - 3]) << endl;
+      return TRACKR.ispusr[mkbmx2 - 3]; // assign parent identity
+   }
+   if (TRACKR.jtrack <= 64){
+       return TRACKR.jtrack;
+   } else {
+       return TRACKR.j0trck;
+   }
+}
+
+
 //______________________________________________________________________________ 
 Int_t TFluka::TrackPid() const
 {
 // Return the id of the particle transported
 // TRACKR.jtrack = identity number of the particle
   FlukaCallerCode_t caller = GetCaller();
-  if (caller != kEEDRAW) {
-      return PDGFromId(TRACKR.jtrack);
+  if (caller != kEEDRAW && caller != kSODRAW) {
+     return PDGFromId( CorrectFlukaId() );
+  }
+  else if (caller == kSODRAW) {
+      return PDGFromId(FLKSTK.iloflk[FLKSTK.npflka]);
   }
   else
     return -1000;
@@ -1513,9 +1847,14 @@ Double_t TFluka::TrackCharge() const
 // Return charge of the track currently transported
 // PAPROP.ichrge = electric charge of the particle
 // TRACKR.jtrack = identity number of the particle
+    
   FlukaCallerCode_t caller = GetCaller();
-  if (caller != kEEDRAW) 
-    return PAPROP.ichrge[TRACKR.jtrack+6];
+  if (caller != kEEDRAW && caller != kSODRAW) 
+     return PAPROP.ichrge[CorrectFlukaId() + 6];
+  else if (caller == kSODRAW) {
+      Int_t ifl =  PDGFromId(FLKSTK.iloflk[FLKSTK.npflka]);
+      return PAPROP.ichrge[ifl + 6];
+  }
   else
     return -1000.0;
 }
@@ -1526,8 +1865,12 @@ Double_t TFluka::TrackMass() const
 // PAPROP.am = particle mass in GeV
 // TRACKR.jtrack = identity number of the particle
   FlukaCallerCode_t caller = GetCaller();
-  if (caller != kEEDRAW)
-    return PAPROP.am[TRACKR.jtrack+6];
+  if (caller != kEEDRAW && caller != kSODRAW)
+     return PAPROP.am[CorrectFlukaId()+6];
+  else if (caller == kSODRAW) {
+      Int_t ifl =  FLKSTK.iloflk[FLKSTK.npflka];
+      return PAPROP.am[ifl + 6];
+  }
   else
     return -1000.0;
 }
@@ -1536,11 +1879,38 @@ Double_t TFluka::TrackMass() const
 Double_t TFluka::Etot() const
 {
 // TRACKR.etrack = total energy of the particle
-  FlukaCallerCode_t caller = GetCaller();
-  if (caller != kEEDRAW)
-    return TRACKR.etrack;
-  else
-    return -1000.0;
+  FlukaCallerCode_t  caller = GetCaller();
+  FlukaProcessCode_t icode  = GetIcode();
+  if (caller != kEEDRAW && caller != kSODRAW && caller != kUSDRAW)
+  {
+      return TRACKR.etrack;
+  } else if (caller == kUSDRAW) {
+      if (icode == kEMFSCObrems  || 
+         icode == kEMFSCOmoller || 
+         icode == kEMFSCObhabha || 
+         icode == kEMFSCOcompton ) {
+         return  fPint[3];
+      }
+      else if (icode == kKASKADdray  || 
+              icode == kKASKADbrems || 
+              icode == kKASKADpair) {
+         return (GENSTK.tki[0] + PAPROP.am[GENSTK.kpart[0]+6]);      
+      } else {
+         return TRACKR.etrack;
+      }
+      
+  }
+  else if (caller == kSODRAW) {
+      Int_t ist  = FLKSTK.npflka;
+      Double_t p = FLKSTK.pmoflk[ist];
+      Int_t ifl  = FLKSTK.iloflk[ist];
+      Double_t m = PAPROP.am[ifl + 6];
+      Double_t e = TMath::Sqrt(p * p + m * m);
+      return e;
+  }
+  printf("Etot %5d %5d \n", caller, icode);
+  
+  return -1000.0;
 }
 
 //
@@ -1634,7 +2004,7 @@ Bool_t   TFluka::IsTrackDisappeared() const
       icode == kEMFSCOcompton    || // Compton scattering
       icode == kEMFSCOphotoel    || // Photoelectric effect
       icode == kKASNEUhadronic   || // hadronic interaction
-      icode == kKASHEAdray        // delta-ray
+      icode == kKASHEAdray          // delta-ray
       ) return 1;
   else return 0;
 }
@@ -1645,24 +2015,40 @@ Bool_t   TFluka::IsTrackStop() const
 // True if the track energy has fallen below the threshold
 // means stopped by signal or below energy threshold
   FlukaProcessCode_t icode = GetIcode();
-  if (icode == kKASKADstopping  ||
-      icode == kKASKADtimekill  ||
-      icode == kEMFSCOstopping1 ||
-      icode == kEMFSCOstopping2 ||
-      icode == kEMFSCOtimekill  ||
-      icode == kKASNEUstopping  ||
-      icode == kKASNEUtimekill  ||
-      icode == kKASHEAtimekill  ||
-      icode == kKASOPHtimekill) return 1;
+  if (icode == kKASKADstopping  || // stopping particle
+      icode == kKASKADtimekill  || // time kill 
+      icode == kEMFSCOstopping1 || // below user-defined cut-off
+      icode == kEMFSCOstopping2 || // below user cut-off
+      icode == kEMFSCOtimekill  || // time kill
+      icode == kKASNEUstopping  || // neutron below threshold
+      icode == kKASNEUtimekill  || // time kill
+      icode == kKASHEAtimekill  || // time kill
+      icode == kKASOPHtimekill) return 1; // time kill
   else return 0;
 }
 
 //______________________________________________________________________________ 
 Bool_t   TFluka::IsTrackAlive() const
 {
-// means not disappeared or not out
-  if (IsTrackDisappeared() || IsTrackOut() ) return 0;
-  else return 1;
+// Means not disappeared or not out
+    FlukaProcessCode_t icode = GetIcode();
+    
+    if (IsTrackOut()               || 
+       IsTrackStop()              ||
+       icode == kKASKADinelint    || // inelastic interaction
+       icode == kKASKADdecay      || // particle decay
+       icode == kEMFSCOanniflight || // in-flight annihilation
+       icode == kEMFSCOannirest   || // annihilation at rest
+       icode == kEMFSCOpair       || // pair production
+       icode == kEMFSCOphotoel    || // Photoelectric effect
+       icode == kKASNEUhadronic      // hadronic interaction
+       ) 
+    {
+       // Exclude the cases for which the particle has disappeared (paused) but will reappear later (= alive).
+       return 0;
+    } else {
+       return 1;
+    }
 }
 
 //
@@ -1678,69 +2064,69 @@ Int_t TFluka::NSecondaries() const
 // FHEAVY.npheav = number of secondaries for light and heavy secondary ions
     FlukaCallerCode_t caller = GetCaller();
     if (caller == kUSDRAW)  // valid only after usdraw
-       return GENSTK.np + FHEAVY.npheav;
+        return GENSTK.np + FHEAVY.npheav;
     else if (caller == kUSTCKV) {
-       // Cerenkov Photon production
-       return fNCerenkov;
+        // Cerenkov Photon production
+        return fNCerenkov;
     }
     return 0;
 } // end of NSecondaries
 
 //______________________________________________________________________________ 
 void TFluka::GetSecondary(Int_t isec, Int_t& particleId,
-               TLorentzVector& position, TLorentzVector& momentum)
+                TLorentzVector& position, TLorentzVector& momentum)
 {
 // Copy particles from secondary stack to vmc stack
 //
 
     FlukaCallerCode_t caller = GetCaller();
     if (caller == kUSDRAW) {  // valid only after usdraw
-       if (GENSTK.np > 0) {
-           // Hadronic interaction
-           if (isec >= 0 && isec < GENSTK.np) {
-               particleId = PDGFromId(GENSTK.kpart[isec]);
-               position.SetX(fXsco);
-               position.SetY(fYsco);
-               position.SetZ(fZsco);
-               position.SetT(TRACKR.atrack);
-               momentum.SetPx(GENSTK.plr[isec]*GENSTK.cxr[isec]);
-               momentum.SetPy(GENSTK.plr[isec]*GENSTK.cyr[isec]);
-               momentum.SetPz(GENSTK.plr[isec]*GENSTK.czr[isec]);
-               momentum.SetE(GENSTK.tki[isec] + PAPROP.am[GENSTK.kpart[isec]+6]);
-           }
-           else if (isec >= GENSTK.np && isec < GENSTK.np + FHEAVY.npheav) {
-               Int_t jsec = isec - GENSTK.np;
-               particleId = FHEAVY.kheavy[jsec]; // this is Fluka id !!!
-               position.SetX(fXsco);
-               position.SetY(fYsco);
-               position.SetZ(fZsco);
-               position.SetT(TRACKR.atrack);
-               momentum.SetPx(FHEAVY.pheavy[jsec]*FHEAVY.cxheav[jsec]);
-               momentum.SetPy(FHEAVY.pheavy[jsec]*FHEAVY.cyheav[jsec]);
-               momentum.SetPz(FHEAVY.pheavy[jsec]*FHEAVY.czheav[jsec]);
-               if (FHEAVY.tkheav[jsec] >= 3 && FHEAVY.tkheav[jsec] <= 6) 
-                   momentum.SetE(FHEAVY.tkheav[jsec] + PAPROP.am[jsec+6]);
-               else if (FHEAVY.tkheav[jsec] > 6)
-                   momentum.SetE(FHEAVY.tkheav[jsec] + FHEAVY.amnhea[jsec]); // to be checked !!!
-           }
-           else
-               Warning("GetSecondary","isec out of range");
-       } 
+        if (GENSTK.np > 0) {
+            // Hadronic interaction
+            if (isec >= 0 && isec < GENSTK.np) {
+                particleId = PDGFromId(GENSTK.kpart[isec]);
+                position.SetX(fXsco);
+                position.SetY(fYsco);
+                position.SetZ(fZsco);
+                position.SetT(TRACKR.atrack);
+                momentum.SetPx(GENSTK.plr[isec]*GENSTK.cxr[isec]);
+                momentum.SetPy(GENSTK.plr[isec]*GENSTK.cyr[isec]);
+                momentum.SetPz(GENSTK.plr[isec]*GENSTK.czr[isec]);
+                momentum.SetE(GENSTK.tki[isec] + PAPROP.am[GENSTK.kpart[isec]+6]);
+            }
+            else if (isec >= GENSTK.np && isec < GENSTK.np + FHEAVY.npheav) {
+                Int_t jsec = isec - GENSTK.np;
+                particleId = FHEAVY.kheavy[jsec]; // this is Fluka id !!!
+                position.SetX(fXsco);
+                position.SetY(fYsco);
+                position.SetZ(fZsco);
+                position.SetT(TRACKR.atrack);
+                momentum.SetPx(FHEAVY.pheavy[jsec]*FHEAVY.cxheav[jsec]);
+                momentum.SetPy(FHEAVY.pheavy[jsec]*FHEAVY.cyheav[jsec]);
+                momentum.SetPz(FHEAVY.pheavy[jsec]*FHEAVY.czheav[jsec]);
+                if (FHEAVY.tkheav[jsec] >= 3 && FHEAVY.tkheav[jsec] <= 6)
+                    momentum.SetE(FHEAVY.tkheav[jsec] + PAPROP.am[jsec+6]);
+                else if (FHEAVY.tkheav[jsec] > 6)
+                    momentum.SetE(FHEAVY.tkheav[jsec] + FHEAVY.amnhea[jsec]); // to be checked !!!
+            }
+            else
+                Warning("GetSecondary","isec out of range");
+        }
     } else if (caller == kUSTCKV) {
-       Int_t index = OPPHST.lstopp - isec;
-       position.SetX(OPPHST.xoptph[index]);
-       position.SetY(OPPHST.yoptph[index]);
-       position.SetZ(OPPHST.zoptph[index]);
-       position.SetT(OPPHST.agopph[index]);
-       Double_t p = OPPHST.poptph[index];
-       
-       momentum.SetPx(p * OPPHST.txopph[index]);
-       momentum.SetPy(p * OPPHST.tyopph[index]);
-       momentum.SetPz(p * OPPHST.tzopph[index]);
-       momentum.SetE(p);
+        Int_t index = OPPHST.lstopp - isec;
+        position.SetX(OPPHST.xoptph[index]);
+        position.SetY(OPPHST.yoptph[index]);
+        position.SetZ(OPPHST.zoptph[index]);
+        position.SetT(OPPHST.agopph[index]);
+        Double_t p = OPPHST.poptph[index];
+        
+        momentum.SetPx(p * OPPHST.txopph[index]);
+        momentum.SetPy(p * OPPHST.tyopph[index]);
+        momentum.SetPz(p * OPPHST.tzopph[index]);
+        momentum.SetE(p);
     }
     else
-       Warning("GetSecondary","no secondaries available");
+        Warning("GetSecondary","no secondaries available");
     
 } // end of GetSecondary
 
@@ -1753,8 +2139,8 @@ TMCProcess TFluka::ProdProcess(Int_t) const
 // in the current step
 
     Int_t mugamma = (TRACKR.jtrack == kFLUKAphoton || 
-                    TRACKR.jtrack == kFLUKAmuplus || 
-                    TRACKR.jtrack == kFLUKAmuminus);
+                     TRACKR.jtrack == kFLUKAmuplus ||
+                     TRACKR.jtrack == kFLUKAmuminus);
     FlukaProcessCode_t icode = GetIcode();
 
     if      (icode == kKASKADdecay)                                   return kPDecay;
@@ -1766,9 +2152,9 @@ TMCProcess TFluka::ProdProcess(Int_t) const
     else if (icode == kEMFSCOmoller     || icode == kEMFSCObhabha)    return kPDeltaRay;
     else if (icode == kEMFSCOanniflight || icode == kEMFSCOannirest)  return kPAnnihilation;
     else if (icode == kKASKADinelint) {
-       if (!mugamma)                                                 return kPHadronic;
-       else if (TRACKR.jtrack == kFLUKAphoton)                       return kPPhotoFission;
-       else                                                          return kPMuonNuclear;
+        if (!mugamma)                                                 return kPHadronic;
+        else if (TRACKR.jtrack == kFLUKAphoton)                       return kPPhotoFission;
+        else                                                          return kPMuonNuclear;
     }
     else if (icode == kEMFSCOrayleigh)                                return kPRayleigh;
 // Fluka codes 100, 300 and 400 still to be investigasted
@@ -1781,39 +2167,78 @@ Int_t TFluka::StepProcesses(TArrayI &proc) const
   //
   // Return processes active in the current step
   //
-    FlukaProcessCode_t icode = GetIcode();
+    FlukaProcessCode_t icode   = GetIcode();
+    FlukaCallerCode_t  caller  = GetCaller();
     proc.Set(1);
     TMCProcess iproc;
-    switch (icode) {
-    case kKASKADtimekill:
-    case kEMFSCOtimekill:
-    case kKASNEUtimekill:
-    case kKASHEAtimekill:
-    case kKASOPHtimekill:
-       iproc =  kPTOFlimit;
-       break;
-    case kKASKADstopping:
-    case kKASKADescape:
-    case kEMFSCOstopping1:
-    case kEMFSCOstopping2:
-    case kEMFSCOescape:
-    case kKASNEUstopping:
-    case kKASNEUescape:
-    case kKASHEAescape:
-    case kKASOPHescape:
-       iproc = kPStop;
-       break;
-    case kKASOPHabsorption:
-       iproc = kPLightAbsorption;
-       break;
-    case kKASOPHrefraction:
-       iproc = kPLightRefraction;
-    case kEMSCOlocaledep : 
-       iproc = kPPhotoelectric;
-       break;
-    default:
-       iproc = ProdProcess(0);
+    if (caller == kBXEntering || caller == kBXExiting || caller == kEEDRAW || caller == kSODRAW) {
+       iproc = kPTransportation;
+    }
+    else if (caller == kUSTCKV) {
+       iproc = kPCerenkov;
+    } else {
+       switch (icode) {
+       case kEMFSCO:
+           if (Edep() > 0.) {
+               iproc = kPEnergyLoss;
+           } else {
+               iproc = kPTransportation;
+           }
+           break;
+       case kKASKAD:
+           if (Edep() > 0.) {
+               iproc = kPEnergyLoss;
+           } else {
+               iproc = kPTransportation;
+           }
+           break;
+       case kKASHEA:
+       case kKASNEU:
+       case kKASOPH:
+       case kKASKADescape:
+       case kEMFSCOescape:
+       case kKASNEUescape:
+       case kKASHEAescape:
+       case kKASOPHescape:
+           iproc = kPTransportation;
+           break;
+       case kKASKADtimekill:
+       case kEMFSCOtimekill:
+       case kKASNEUtimekill:
+       case kKASHEAtimekill:
+       case kKASOPHtimekill:
+           iproc =  kPTOFlimit;
+           break;
+       case kKASKADstopping:
+       case kEMFSCOstopping1:
+       case kEMFSCOstopping2:
+       case kKASNEUstopping:
+           iproc = kPStop;
+           break; 
+       case kKASKADinelint:
+       case kKASNEUhadronic:
+           iproc = kPHadronic;
+           break;
+       case kKASKADinelarecoil:
+           iproc = kPHadronic;
+           break;
+       case kKASKADnelint:
+           iproc = kPHElastic;
+           break;
+       case kKASOPHabsorption:
+           iproc = kPLightAbsorption;
+           break;
+       case kKASOPHrefraction:
+           iproc = kPLightRefraction;
+           break;
+       case kEMFSCOlocaldep : 
+           iproc = kPPhotoelectric;
+           break;
+       default:
+           iproc = ProdProcess(0);
+       }
     }
+    
     proc[0] = iproc;
     return 1;
 }
@@ -1835,6 +2260,19 @@ const char* TFluka::VolName(Int_t id) const
    return fMCGeo->VolName(id);
 }
 
+Int_t TFluka::MediumId(const Text_t* mediumName) const
+{
+    //
+    // Return the unique medium id for medium with name mediumName
+    TList *medlist = gGeoManager->GetListOfMedia();
+    TGeoMedium* med = (TGeoMedium*) medlist->FindObject(mediumName);
+    if (med) {
+       return (med->GetId());
+    } else {
+       return (-1);
+    }
+}
+
 //______________________________________________________________________________ 
 Int_t TFluka::VolId(const Text_t* volName) const
 {
@@ -1885,7 +2323,7 @@ const char* TFluka::CurrentVolName() const
 //
 // Return the current volume name
 //
-  if (gGeoManager->IsOutside()) return 0;
+  if (gGeoManager->IsOutside()) return "OutOfWorld";
   return gGeoManager->GetCurrentVolume()->GetName();
 }
 
@@ -1908,7 +2346,7 @@ const char* TFluka::CurrentVolPath() {
 }
 //______________________________________________________________________________ 
 Int_t TFluka::CurrentMaterial(Float_t & a, Float_t & z, 
-                     Float_t & dens, Float_t & radl, Float_t & absl) const
+                      Float_t & dens, Float_t & radl, Float_t & absl) const
 {
 //
 //  Return the current medium number and material properties
@@ -1958,6 +2396,9 @@ void TFluka::Gmtod(Float_t* xm, Float_t* xd, Int_t iflag)
 //______________________________________________________________________________ 
 void TFluka::Gmtod(Double_t* xm, Double_t* xd, Int_t iflag)
 {
+//
+// See Gmtod(Float_t*, Float_t*, Int_t)
+//
    if (iflag == 1) gGeoManager->MasterToLocal(xm,xd);
    else            gGeoManager->MasterToLocalVect(xm,xd);
 }
@@ -1992,6 +2433,9 @@ void TFluka::Gdtom(Float_t* xd, Float_t* xm, Int_t iflag)
 //______________________________________________________________________________ 
 void TFluka::Gdtom(Double_t* xd, Double_t* xm, Int_t iflag)
 {
+//
+// See Gdtom(Float_t*, Float_t*, Int_t)
+//
    if (iflag == 1) gGeoManager->LocalToMaster(xd,xm);
    else            gGeoManager->LocalToMasterVect(xd,xm);
 }
@@ -1999,6 +2443,8 @@ void TFluka::Gdtom(Double_t* xd, Double_t* xm, Int_t iflag)
 //______________________________________________________________________________
 TObjArray *TFluka::GetFlukaMaterials()
 {
+//
+// Get array of Fluka materials
    return fGeom->GetMatList();
 }   
 
@@ -2013,6 +2459,7 @@ void TFluka::SetMreg(Int_t l, Int_t lttc)
 
 
 
+//______________________________________________________________________________
 TString TFluka::ParticleName(Int_t pdg) const
 {
     // Return particle name for particle with pdg code pdg.
@@ -2021,6 +2468,7 @@ TString TFluka::ParticleName(Int_t pdg) const
 }
  
 
+//______________________________________________________________________________
 Double_t TFluka::ParticleMass(Int_t pdg) const
 {
     // Return particle mass for particle with pdg code pdg.
@@ -2028,12 +2476,14 @@ Double_t TFluka::ParticleMass(Int_t pdg) const
     return (PAPROP.am[ifluka - kFLUKAcodemin]);
 }
 
+//______________________________________________________________________________
 Double_t TFluka::ParticleMassFPC(Int_t fpc) const
 {
     // Return particle mass for particle with Fluka particle code fpc
     return (PAPROP.am[fpc - kFLUKAcodemin]);
 }
 
+//______________________________________________________________________________
 Double_t TFluka::ParticleCharge(Int_t pdg) const
 {
     // Return particle charge for particle with pdg code pdg.
@@ -2041,6 +2491,7 @@ Double_t TFluka::ParticleCharge(Int_t pdg) const
     return Double_t(PAPROP.ichrge[ifluka - kFLUKAcodemin]);
 }
 
+//______________________________________________________________________________
 Double_t TFluka::ParticleLifeTime(Int_t pdg) const
 {
     // Return particle lifetime for particle with pdg code pdg.
@@ -2048,6 +2499,7 @@ Double_t TFluka::ParticleLifeTime(Int_t pdg) const
     return (PAPROP.tmnlf[ifluka - kFLUKAcodemin]);
 }
 
+//______________________________________________________________________________
 void TFluka::Gfpart(Int_t pdg, char* name, Int_t& type, Float_t& mass, Float_t& charge, Float_t& tlife)
 {
     // Retrieve particle properties for particle with pdg code pdg.
@@ -2059,6 +2511,7 @@ void TFluka::Gfpart(Int_t pdg, char* name, Int_t& type, Float_t& mass, Float_t&
     tlife  = ParticleLifeTime(pdg);
 }
 
+//______________________________________________________________________________
 void TFluka::PrintHeader()
 {
     //
@@ -2080,8 +2533,8 @@ void TFluka::PrintHeader()
 
 extern "C" {
   void pshckp(Double_t & px, Double_t & py, Double_t & pz, Double_t & e,
-             Double_t & vx, Double_t & vy, Double_t & vz, Double_t & tof,
-             Double_t & polx, Double_t & poly, Double_t & polz, Double_t & wgt, Int_t& ntr)
+              Double_t & vx, Double_t & vy, Double_t & vz, Double_t & tof,
+              Double_t & polx, Double_t & poly, Double_t & polz, Double_t & wgt, Int_t& ntr)
   {
     //
     // Pushes one cerenkov photon to the stack
@@ -2091,27 +2544,229 @@ extern "C" {
     TVirtualMCStack* cppstack = fluka->GetStack();
     Int_t parent =  TRACKR.ispusr[mkbmx2-1];
     cppstack->PushTrack(0, parent, 50000050,
-                       px, py, pz, e,
-                       vx, vy, vz, tof,
-                       polx, poly, polz,
-                       kPCerenkov, ntr, wgt, 0);
+                        px, py, pz, e,
+                        vx, vy, vz, tof,
+                        polx, poly, polz,
+                        kPCerenkov, ntr, wgt, 0);
+    if (fluka->GetVerbosityLevel() >= 3)
+            printf("pshckp: track=%d parent=%d lattc=%d %s\n", ntr, parent, TRACKR.lt1trk, fluka->CurrentVolName());
   }
     
     void ustckv(Int_t & nphot, Int_t & mreg, Double_t & x, Double_t & y, Double_t & z)
     {
-       //
-       // Calls stepping in order to signal cerenkov production
-       //
-       TFluka *fluka = (TFluka*)gMC;
-       fluka->SetMreg(mreg,LTCLCM.mlatm1);
-       fluka->SetXsco(x);
-       fluka->SetYsco(y);
-       fluka->SetZsco(z);
-       fluka->SetNCerenkov(nphot);
-       fluka->SetCaller(kUSTCKV);
-       if (fluka->GetVerbosityLevel() >= 3) 
+        //
+        // Calls stepping in order to signal cerenkov production
+        //
+        TFluka *fluka = (TFluka*)gMC;
+        fluka->SetMreg(mreg, TRACKR.lt1trk); //LTCLCM.mlatm1);
+        fluka->SetXsco(x);
+        fluka->SetYsco(y);
+        fluka->SetZsco(z);
+        fluka->SetNCerenkov(nphot);
+        fluka->SetCaller(kUSTCKV);
+        if (fluka->GetVerbosityLevel() >= 3)
+            printf("ustckv: %10d mreg=%d lattc=%d  newlat=%d (%f, %f, %f) edep=%f vol=%s\n",
+                    nphot, mreg, TRACKR.lt1trk, LTCLCM.newlat, x, y, z, fluka->Edep(), fluka->CurrentVolName());
+   
+    // check region lattice consistency (debug Ernesto)
+    // *****************************************************
+   Int_t nodeId;
+   Int_t volId = fluka->CurrentVolID(nodeId);
+   Int_t crtlttc = gGeoManager->GetCurrentNodeId()+1;
+
+   if( mreg != volId  && !gGeoManager->IsOutside() ) {
+       cout << "  ustckv:   track=" << TRACKR.ispusr[mkbmx2-1] << " pdg=" << fluka->PDGFromId(TRACKR.jtrack)
+            << " icode=" << fluka->GetIcode() << " gNstep=" << fluka->GetNstep() << endl
+            << "               fluka   mreg=" << mreg << " mlttc=" << TRACKR.lt1trk << endl
+            << "               TGeo   volId=" << volId << " crtlttc=" << crtlttc << endl
+            << "     common TRACKR   lt1trk=" << TRACKR.lt1trk << " lt2trk=" << TRACKR.lt2trk << endl
+            << "     common LTCLCM   newlat=" << LTCLCM.newlat << " mlatld=" <<  LTCLCM.mlatld << endl
+            << "                     mlatm1=" << LTCLCM.mlatm1 << " mltsen=" <<  LTCLCM.mltsen << endl
+            << "                     mltsm1=" << LTCLCM.mltsm1 << " mlattc=" << LTCLCM.mlattc << endl;
+        if( TRACKR.lt1trk == crtlttc ) cout << "   *************************************************************" << endl;
+    }
+    // *****************************************************
+
+
+
+        (TVirtualMCApplication::Instance())->Stepping();
+    }
+}
+
+//______________________________________________________________________________
+void TFluka::AddParticlesToPdgDataBase() const
+{
+
+//
+// Add particles to the PDG data base
+
+    TDatabasePDG *pdgDB = TDatabasePDG::Instance();
+
+    const Double_t kAu2Gev   = 0.9314943228;
+    const Double_t khSlash   = 1.0545726663e-27;
+    const Double_t kErg2Gev  = 1/1.6021773349e-3;
+    const Double_t khShGev   = khSlash*kErg2Gev;
+    const Double_t kYear2Sec = 3600*24*365.25;
+//
+// Ions
+//
+  pdgDB->AddParticle("Deuteron","Deuteron",2*kAu2Gev+8.071e-3,kTRUE,
+                     0,3,"Ion",TFlukaIon::GetIonPdg(1,2));
+  pdgDB->AddParticle("Triton","Triton",3*kAu2Gev+14.931e-3,kFALSE,
+                     khShGev/(12.33*kYear2Sec),3,"Ion",TFlukaIon::GetIonPdg(1,3));
+  pdgDB->AddParticle("Alpha","Alpha",4*kAu2Gev+2.424e-3,kTRUE,
+                     khShGev/(12.33*kYear2Sec),6,"Ion",TFlukaIon::GetIonPdg(2,4));
+  pdgDB->AddParticle("HE3","HE3",3*kAu2Gev+14.931e-3,kFALSE,
+                     0,6,"Ion",TFlukaIon::GetIonPdg(2,3));
+  
+//
+//
+//
+// Special particles
+//
+  pdgDB->AddParticle("Cherenkov","Cherenkov",0,kFALSE,
+                     0,0,"Special",GetSpecialPdg(50));
+  pdgDB->AddParticle("FeedbackPhoton","FeedbackPhoton",0,kFALSE,
+                     0,0,"Special",GetSpecialPdg(51));
+}
+
+
+//
+// Info about primary ionization electrons
+//
+
+//______________________________________________________________________________
+Int_t TFluka::GetNPrimaryElectrons()
+{
+    // Get number of primary electrons
+    return ALLDLT.nalldl;
+}
+
+//______________________________________________________________________________
+Double_t TFluka::GetPrimaryElectronKineticEnergy(Int_t i) const
+{
+    // Returns kinetic energy of primary electron i
+
+    Double_t ekin = -1.;
+    
+    if (i >= 0 && i < ALLDLT.nalldl) {
+        ekin =  ALLDLT.talldl[i];
+    } else {
+        Warning("GetPrimaryElectronKineticEnergy",
+                "Primary electron index out of range %d %d \n",
+                i, ALLDLT.nalldl);
+    }
+    return ekin;
+}
+
+void TFluka::GetPrimaryElectronPosition(Int_t i, Double_t& x, Double_t& y, Double_t& z, Double_t& t) const
+{
+    // Returns position  of primary electron i
+        if (i >= 0 && i < ALLDLT.nalldl) {
+           x = ALLDLT.xalldl[i];
+           y = ALLDLT.yalldl[i];
+           z = ALLDLT.zalldl[i];
+           t = ALLDLT.talldl[i];
+           return;
+       } else {
+           Warning("GetPrimaryElectronPosition",
+                   "Primary electron index out of range %d %d \n",
+                   i, ALLDLT.nalldl);
+           return;
+       }
+       return;
+}
+
+
+//__________________________________________________________________
+Int_t TFluka::GetSpecialPdg(Int_t number) const
+{
+// Numbering for special particles
+
+  return 50000000 + number;
+}                
+
+     
+void  TFluka::PrimaryIonisationStepping(Int_t nprim)
+{
+// Call Stepping for primary ionisation electrons
+// Protection against nprim > mxalld
+// Multiple steps for nprim > 0
+    Int_t i;
+    fNPI = nprim;
+    if (nprim > 0) {
+       CalcPrimaryIonisationTime();
+       for (i = 0; i < nprim; i++) {
+           SetCurrentPrimaryElectronIndex(i);
+           (TVirtualMCApplication::Instance())->Stepping();
+           if (i == 0) SetTrackIsNew(kFALSE);
+       }       
+    } else {
+       // No primary electron ionisation
+       // Call Stepping anyway but flag nprim = 0 as index = -2
+       SetCurrentPrimaryElectronIndex(-2);
        (TVirtualMCApplication::Instance())->Stepping();
-       
     }
+    // Reset the index
+    SetCurrentPrimaryElectronIndex(-1);
 }
 
+//______________________________________________________________________
+Float_t* TFluka::CreateFloatArray(Double_t* array, Int_t size) const
+{
+// Converts Double_t* array to Float_t*,
+// !! The new array has to be deleted by user.
+// ---
+    
+  Float_t* floatArray;
+  if (size>0) {
+    floatArray = new Float_t[size];
+    for (Int_t i=0; i<size; i++)
+      if (array[i] >= FLT_MAX ) 
+        floatArray[i] = FLT_MAX/100.;
+      else     
+        floatArray[i] = array[i];
+  }
+  else {
+    //floatArray = 0;
+    floatArray = new Float_t[1];
+  }
+  return floatArray;
+}
+
+void TFluka::CalcPrimaryIonisationTime()
+{
+    // Calculates the primary ionisation time
+    if (fPItime) delete [] fPItime; 
+    fPItime = new Double_t[fNPI];
+    if (fPIlength) delete [] fPIlength;
+    fPIlength = new Double_t[fNPI];
+    //
+    Double_t px, py, pz, e, t;
+    TrackMomentum(px, py, pz, e);
+    Double_t p    = TMath::Sqrt(px * px + py * py + pz * pz);
+    Double_t beta = p / e;
+    Double_t x0, y0, z0;
+    fPItime[fNPI -1]   = TRACKR.atrack;
+    fPIlength[fNPI -1] = TRACKR.cmtrck;
+    GetPrimaryElectronPosition(fNPI - 1, x0, y0, z0, t);       
+    if (fNPI > 1) {
+       for (Int_t i = fNPI - 2; i > -1; i--) {
+           Double_t x, y, z, t;
+           GetPrimaryElectronPosition(i, x, y, z, t);  
+           Double_t ds = TMath::Sqrt((x-x0) * (x-x0) + (y-y0) * (y-y0) + (z-z0) * (z-z0));
+           fPItime[i]   = fPItime[i+1]   - ds / (beta * 2.99792458e10);
+           fPIlength[i] = fPIlength[i+1] - ds;
+           x0 = x; y0 = y; z0 = z;
+       }
+    }
+    
+}
+
+Bool_t TFluka::DefineIon(const char* name , Int_t z, Int_t a, Int_t q, Double_t exE, Double_t mass)
+{
+    // User defined ion that can be used as a primary
+    fUserIons = kTRUE;
+    TFlukaIon::AddIon(name, z, a, q,exE, mass);
+    return kTRUE;
+}