]> git.uio.no Git - u/mrichter/AliRoot.git/blob - TFluka/TFluka.cxx
Correct initialization of optical properties needed by Geant4 (Andrei)
[u/mrichter/AliRoot.git] / TFluka / TFluka.cxx
1 /**************************************************************************
2  * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
3  *                                                                        *
4  * Author: The ALICE Off-line Project.                                    *
5  * Contributors are mentioned in the code where appropriate.              *
6  *                                                                        *
7  * Permission to use, copy, modify and distribute this software and its   *
8  * documentation strictly for non-commercial purposes is hereby granted   *
9  * without fee, provided that the above copyright notice appears in all   *
10  * copies and that both the copyright notice and this permission notice   *
11  * appear in the supporting documentation. The authors make no claims     *
12  * about the suitability of this software for any purpose. It is          *
13  * provided "as is" without express or implied warranty.                  *
14  **************************************************************************/
15
16 /* $Id$ */
17
18 //
19 // Realisation of the TVirtualMC interface for the FLUKA code
20 // (See official web side http://www.fluka.org/).
21 //
22 // This implementation makes use of the TGeo geometry modeller.
23 // User configuration is via automatic generation of FLUKA input cards.
24 //
25 // Authors:
26 // A. Fasso
27 // E. Futo
28 // A. Gheata
29 // A. Morsch
30 //
31
32 #include <Riostream.h>
33
34 #include "TFluka.h"
35 #include "TFlukaCodes.h"
36 #include "TCallf77.h"      //For the fortran calls
37 #include "Fdblprc.h"       //(DBLPRC) fluka common
38 #include "Fsourcm.h"       //(SOURCM) fluka common
39 #include "Fgenstk.h"       //(GENSTK)  fluka common
40 #include "Fiounit.h"       //(IOUNIT) fluka common
41 #include "Fpaprop.h"       //(PAPROP) fluka common
42 #include "Fpart.h"         //(PART)   fluka common
43 #include "Ftrackr.h"       //(TRACKR) fluka common
44 #include "Fpaprop.h"       //(PAPROP) fluka common
45 #include "Ffheavy.h"       //(FHEAVY) fluka common
46 #include "Fopphst.h"       //(OPPHST) fluka common
47 #include "Fflkstk.h"       //(FLKSTK) fluka common
48 #include "Fstepsz.h"       //(STEPSZ) fluka common
49 #include "Fopphst.h"       //(OPPHST) fluka common
50 #include "Fltclcm.h"       //(LTCLCM) fluka common
51 #include "Falldlt.h"       //(ALLDLT) fluka common
52
53 #include "TVirtualMC.h"
54 #include "TMCProcess.h"
55 #include "TGeoManager.h"
56 #include "TGeoMaterial.h"
57 #include "TGeoMedium.h"
58 #include "TFlukaMCGeometry.h"
59 #include "TGeoMCGeometry.h"
60 #include "TFlukaCerenkov.h"
61 #include "TFlukaConfigOption.h"
62 #include "TFlukaScoringOption.h"
63 #include "TLorentzVector.h"
64 #include "TArrayI.h"
65 #include "TArrayD.h"
66 #include "TDatabasePDG.h"
67 #include "TStopwatch.h"
68
69
70 // Fluka methods that may be needed.
71 #ifndef WIN32 
72 # define flukam  flukam_
73 # define fluka_openinp fluka_openinp_
74 # define fluka_openout fluka_openout_
75 # define fluka_closeinp fluka_closeinp_
76 # define mcihad mcihad_
77 # define mpdgha mpdgha_
78 # define newplo newplo_
79 # define genout genout_
80 # define flkend flkend_
81 #else 
82 # define flukam  FLUKAM
83 # define fluka_openinp FLUKA_OPENINP
84 # define fluka_openout FLUKA_OPENOUT
85 # define fluka_closeinp FLUKA_CLOSEINP
86 # define mcihad MCIHAD
87 # define mpdgha MPDGHA
88 # define newplo NEWPLO
89 # define genout GENOUT
90 # define flkend FLKEND
91 #endif
92
93 extern "C" 
94 {
95   //
96   // Prototypes for FLUKA functions
97   //
98   void type_of_call flukam(const int&);
99   void type_of_call newplo();
100   void type_of_call genout();
101   void type_of_call flkend();
102   void type_of_call fluka_openinp(const int&, DEFCHARA);
103   void type_of_call fluka_openout(const int&, DEFCHARA);
104   void type_of_call fluka_closeinp(const int&);
105   int  type_of_call mcihad(const int&);
106   int  type_of_call mpdgha(const int&);
107 }
108
109 //
110 // Class implementation for ROOT
111 //
112 ClassImp(TFluka)
113
114 //
115 //----------------------------------------------------------------------------
116 // TFluka constructors and destructors.
117 //______________________________________________________________________________
118 TFluka::TFluka()
119   :TVirtualMC(),
120    fVerbosityLevel(0),
121    fNEvent(0),
122    fInputFileName(""),
123    fCoreInputFileName(""),
124    fCaller(kNoCaller),
125    fIcode(kNoProcess),
126    fNewReg(-1),
127    fRull(0),
128    fXsco(0),
129    fYsco(0),
130    fZsco(0),
131    fTrackIsEntering(kFALSE),
132    fTrackIsExiting(kFALSE),
133    fTrackIsNew(kFALSE),
134    fFieldFlag(kTRUE),
135    fGeneratePemf(kFALSE),
136    fDummyBoundary(kFALSE),
137    fStopped(kFALSE),
138    fStopEvent(kFALSE),
139    fStopRun(kFALSE),
140    fPrimaryElectronIndex(-1),
141    fMaterials(0),
142    fNVolumes(0),
143    fCurrentFlukaRegion(-1),
144    fNCerenkov(0),
145    fGeom(0),
146    fMCGeo(0),
147    fUserConfig(0), 
148    fUserScore(0)
149
150   //
151   // Default constructor
152   //
153
154  
155 //______________________________________________________________________________ 
156 TFluka::TFluka(const char *title, Int_t verbosity, Bool_t isRootGeometrySupported)
157   :TVirtualMC("TFluka",title, isRootGeometrySupported),
158    fVerbosityLevel(verbosity),
159    fNEvent(0),
160    fInputFileName(""),
161    fCoreInputFileName(""),
162    fCaller(kNoCaller),
163    fIcode(kNoProcess),
164    fNewReg(-1),
165    fRull(0),
166    fXsco(0),
167    fYsco(0),
168    fZsco(0),
169    fTrackIsEntering(kFALSE),
170    fTrackIsExiting(kFALSE),
171    fTrackIsNew(kFALSE),
172    fFieldFlag(kTRUE),
173    fGeneratePemf(kFALSE),
174    fDummyBoundary(kFALSE),
175    fStopped(kFALSE),
176    fStopEvent(kFALSE),
177    fStopRun(kFALSE),
178    fPrimaryElectronIndex(-1),
179    fMaterials(0),
180    fNVolumes(0),
181    fCurrentFlukaRegion(-1),
182    fNCerenkov(0),
183    fGeom(0),
184    fMCGeo(0),
185    fUserConfig(new TObjArray(100)),
186    fUserScore(new TObjArray(100)) 
187 {
188   // create geometry interface
189    if (fVerbosityLevel >=3)
190        cout << "<== TFluka::TFluka(" << title << ") constructor called." << endl;
191    SetCoreInputFileName();
192    SetInputFileName();
193    fMCGeo = new TGeoMCGeometry("MCGeo", "TGeo Implementation of VirtualMCGeometry", kFALSE);
194    fGeom  = new TFlukaMCGeometry("geom", "FLUKA VMC Geometry");
195    if (verbosity > 2) fGeom->SetDebugMode(kTRUE);
196    PrintHeader();
197 }
198
199 //______________________________________________________________________________ 
200 TFluka::~TFluka()
201 {
202     // Destructor
203     if (fVerbosityLevel >=3)
204         cout << "<== TFluka::~TFluka() destructor called." << endl;
205     if (fMaterials) delete [] fMaterials;
206     
207     delete fGeom;
208     delete fMCGeo;
209     
210     if (fUserConfig) {
211         fUserConfig->Delete();
212         delete fUserConfig;
213     }
214     
215     if (fUserScore) {
216         fUserScore->Delete();
217         delete fUserScore;
218     }
219 }
220
221 //
222 //______________________________________________________________________________
223 // TFluka control methods
224 //______________________________________________________________________________ 
225 void TFluka::Init() {
226 //
227 //  Geometry initialisation
228 //
229     if (fVerbosityLevel >=3) cout << "==> TFluka::Init() called." << endl;
230     
231     if (!gGeoManager) new TGeoManager("geom", "FLUKA geometry");
232     fApplication->ConstructGeometry();
233     if (!gGeoManager->IsClosed()) {
234        TGeoVolume *top = (TGeoVolume*)gGeoManager->GetListOfVolumes()->First();
235        gGeoManager->SetTopVolume(top);
236        gGeoManager->CloseGeometry("di");
237     } else {
238        TGeoNodeCache *cache = gGeoManager->GetCache();
239        if (!cache->HasIdArray()) {
240           Warning("Init", "Node ID tracking must be enabled with TFluka: enabling...\n");
241           cache->BuildIdArray();
242        }   
243     }           
244     fNVolumes = fGeom->NofVolumes();
245     fGeom->CreateFlukaMatFile("flukaMat.inp");   
246     if (fVerbosityLevel >=3) {
247        printf("== Number of volumes: %i\n ==", fNVolumes);
248        cout << "\t* InitPhysics() - Prepare input file to be called" << endl; 
249     }
250
251     fApplication->InitGeometry();
252     fApplication->ConstructOpGeometry();
253     //
254     // Add ions to PDG Data base
255     //
256      AddParticlesToPdgDataBase();
257 }
258
259
260 //______________________________________________________________________________ 
261 void TFluka::FinishGeometry() {
262 //
263 // Build-up table with region to medium correspondance
264 //
265   if (fVerbosityLevel >=3) {
266     cout << "==> TFluka::FinishGeometry() called." << endl;
267     printf("----FinishGeometry - nothing to do with TGeo\n");
268     cout << "<== TFluka::FinishGeometry() called." << endl;
269   }  
270
271
272 //______________________________________________________________________________ 
273 void TFluka::BuildPhysics() {
274 //
275 //  Prepare FLUKA input files and call FLUKA physics initialisation
276 //
277     
278     if (fVerbosityLevel >=3)
279         cout << "==> TFluka::BuildPhysics() called." << endl;
280
281     
282     if (fVerbosityLevel >=3) {
283         TList *medlist = gGeoManager->GetListOfMedia();
284         TIter next(medlist);
285         TGeoMedium*   med = 0x0;
286         TGeoMaterial* mat = 0x0;
287         Int_t ic = 0;
288         
289         while((med = (TGeoMedium*)next()))
290         {
291             mat = med->GetMaterial();
292             printf("Medium %5d %12s %5d %5d\n", ic, (med->GetName()), med->GetId(), mat->GetIndex());
293             ic++;
294         }
295     }
296     
297     //
298     // At this stage we have the information on materials and cuts available.
299     // Now create the pemf file
300     
301     if (fGeneratePemf) fGeom->CreatePemfFile();
302     
303     //
304     // Prepare input file with the current physics settings
305     
306     InitPhysics(); 
307 //  Open fortran files    
308     const char* fname = fInputFileName;
309     fluka_openinp(lunin, PASSCHARA(fname));
310     fluka_openout(11, PASSCHARA("fluka.out"));
311 //  Read input cards    
312     cout << "==> TFluka::BuildPhysics() Read input cards." << endl;
313     TStopwatch timer;
314     timer.Start();
315     GLOBAL.lfdrtr = true;
316     flukam(1);
317     cout << "<== TFluka::BuildPhysics() Read input cards End"
318          << Form(" R:%.2fs C:%.2fs", timer.RealTime(),timer.CpuTime()) << endl;
319 //  Close input file
320     fluka_closeinp(lunin);
321 //  Finish geometry    
322     FinishGeometry();
323 }  
324
325 //______________________________________________________________________________ 
326 void TFluka::ProcessEvent() {
327 //
328 // Process one event
329 //
330     if (fStopRun) {
331         Warning("ProcessEvent", "User Run Abortion: No more events handled !\n");
332         fNEvent += 1;
333         return;
334     }
335
336     if (fVerbosityLevel >=3)
337         cout << "==> TFluka::ProcessEvent() called." << endl;
338     fApplication->GeneratePrimaries();
339     SOURCM.lsouit = true;
340     flukam(1);
341     if (fVerbosityLevel >=3)
342         cout << "<== TFluka::ProcessEvent() called." << endl;
343     //
344     // Increase event number
345     //
346     fNEvent += 1;
347 }
348
349 //______________________________________________________________________________ 
350 Bool_t TFluka::ProcessRun(Int_t nevent) {
351 //
352 // Run steering
353 //
354
355   if (fVerbosityLevel >=3)
356     cout << "==> TFluka::ProcessRun(" << nevent << ") called." 
357          << endl;
358
359   if (fVerbosityLevel >=2) {
360     cout << "\t* GLOBAL.fdrtr = " << (GLOBAL.lfdrtr?'T':'F') << endl;
361     cout << "\t* Calling flukam again..." << endl;
362   }
363
364   Int_t todo = TMath::Abs(nevent);
365   for (Int_t ev = 0; ev < todo; ev++) {
366       TStopwatch timer;
367       timer.Start();
368       fApplication->BeginEvent();
369       ProcessEvent();
370       fApplication->FinishEvent();
371       cout << "Event: "<< ev
372            << Form(" R:%.2fs C:%.2fs", timer.RealTime(),timer.CpuTime()) << endl;
373   }
374
375   if (fVerbosityLevel >=3)
376     cout << "<== TFluka::ProcessRun(" << nevent << ") called." 
377          << endl;
378   
379   // Write fluka specific scoring output
380   genout();
381   newplo();
382   flkend();
383   
384   return kTRUE;
385 }
386
387 //_____________________________________________________________________________
388 // methods for building/management of geometry
389
390 // functions from GCONS 
391 //____________________________________________________________________________ 
392 void TFluka::Gfmate(Int_t imat, char *name, Float_t &a, Float_t &z,  
393                     Float_t &dens, Float_t &radl, Float_t &absl,
394                     Float_t* /*ubuf*/, Int_t& /*nbuf*/) {
395 //
396    TGeoMaterial *mat;
397    TIter next (gGeoManager->GetListOfMaterials());
398    while ((mat = (TGeoMaterial*)next())) {
399      if (mat->GetUniqueID() == (UInt_t)imat) break;
400    }
401    if (!mat) {
402       Error("Gfmate", "no material with index %i found", imat);
403       return;
404    }
405    sprintf(name, "%s", mat->GetName());
406    a = mat->GetA();
407    z = mat->GetZ();
408    dens = mat->GetDensity();
409    radl = mat->GetRadLen();
410    absl = mat->GetIntLen();
411
412
413 //______________________________________________________________________________ 
414 void TFluka::Gfmate(Int_t imat, char *name, Double_t &a, Double_t &z,  
415                     Double_t &dens, Double_t &radl, Double_t &absl,
416                     Double_t* /*ubuf*/, Int_t& /*nbuf*/) {
417 //
418    TGeoMaterial *mat;
419    TIter next (gGeoManager->GetListOfMaterials());
420    while ((mat = (TGeoMaterial*)next())) {
421      if (mat->GetUniqueID() == (UInt_t)imat) break;
422    }
423    if (!mat) {
424       Error("Gfmate", "no material with index %i found", imat);
425       return;
426    }
427    sprintf(name, "%s", mat->GetName());
428    a = mat->GetA();
429    z = mat->GetZ();
430    dens = mat->GetDensity();
431    radl = mat->GetRadLen();
432    absl = mat->GetIntLen();
433
434
435 // detector composition
436 //______________________________________________________________________________ 
437 void TFluka::Material(Int_t& kmat, const char* name, Double_t a, 
438                       Double_t z, Double_t dens, Double_t radl, Double_t absl,
439                       Float_t* buf, Int_t nwbuf) {
440 //
441    Double_t* dbuf = fGeom->CreateDoubleArray(buf, nwbuf);  
442    Material(kmat, name, a, z, dens, radl, absl, dbuf, nwbuf);
443    delete [] dbuf;
444
445
446 //______________________________________________________________________________ 
447 void TFluka::Material(Int_t& kmat, const char* name, Double_t a, 
448                       Double_t z, Double_t dens, Double_t radl, Double_t absl,
449                       Double_t* /*buf*/, Int_t /*nwbuf*/) {
450 //
451 // Define a material
452   TGeoMaterial *mat;
453   kmat = gGeoManager->GetListOfMaterials()->GetSize();
454   if ((z-Int_t(z)) > 1E-3) {
455      mat = fGeom->GetMakeWrongMaterial(z);
456      if (mat) {
457         mat->SetRadLen(radl,absl);
458         mat->SetUniqueID(kmat);
459         return;
460      }
461   }      
462   gGeoManager->Material(name, a, z, dens, kmat, radl, absl);
463
464
465 //______________________________________________________________________________ 
466 void TFluka::Mixture(Int_t& kmat, const char *name, Float_t *a, 
467                      Float_t *z, Double_t dens, Int_t nlmat, Float_t *wmat) {
468 //
469 // Define a material mixture
470 //
471   Double_t* da = fGeom->CreateDoubleArray(a, TMath::Abs(nlmat));  
472   Double_t* dz = fGeom->CreateDoubleArray(z, TMath::Abs(nlmat));  
473   Double_t* dwmat = fGeom->CreateDoubleArray(wmat, TMath::Abs(nlmat));  
474
475   Mixture(kmat, name, da, dz, dens, nlmat, dwmat);
476   for (Int_t i=0; i<nlmat; i++) {
477     a[i] = da[i]; z[i] = dz[i]; wmat[i] = dwmat[i];
478   }  
479
480   delete [] da;
481   delete [] dz;
482   delete [] dwmat;
483
484
485 //______________________________________________________________________________ 
486 void TFluka::Mixture(Int_t& kmat, const char *name, Double_t *a, 
487                      Double_t *z, Double_t dens, Int_t nlmat, Double_t *wmat) {
488 //
489   // Defines mixture OR COMPOUND IMAT as composed by 
490   // THE BASIC NLMAT materials defined by arrays A,Z and WMAT
491   // 
492   // If NLMAT > 0 then wmat contains the proportion by
493   // weights of each basic material in the mixture. 
494   // 
495   // If nlmat < 0 then WMAT contains the number of atoms 
496   // of a given kind into the molecule of the COMPOUND
497   // In this case, WMAT in output is changed to relative
498   // weigths.
499   //
500   Int_t i,j;
501   if (nlmat < 0) {
502      nlmat = - nlmat;
503      Double_t amol = 0;
504      for (i=0;i<nlmat;i++) {
505         amol += a[i]*wmat[i];
506      }
507      for (i=0;i<nlmat;i++) {
508         wmat[i] *= a[i]/amol;
509      }
510   }
511   kmat = gGeoManager->GetListOfMaterials()->GetSize();
512   // Check if we have elements with fractional Z
513   TGeoMaterial *mat = 0;
514   TGeoMixture *mix = 0;
515   Bool_t mixnew = kFALSE;
516   for (i=0; i<nlmat; i++) {
517      if (z[i]-Int_t(z[i]) < 1E-3) continue;
518      // We have found an element with fractional Z -> loop mixtures to look for it
519      for (j=0; j<kmat; j++) {
520         mat = (TGeoMaterial*)gGeoManager->GetListOfMaterials()->At(j);
521         if (!mat) break;
522         if (!mat->IsMixture()) continue;
523         mix = (TGeoMixture*)mat;
524         if (TMath::Abs(z[i]-mix->GetZ()) >1E-3) continue;
525         mixnew = kTRUE;
526         break;
527      }
528      if (!mixnew) Warning("Mixture","%s : cannot find component %i with fractional Z=%f\n", name, i, z[i]);
529      break;
530   }   
531   if (mixnew) {
532      Int_t nlmatnew = nlmat+mix->GetNelements()-1;
533      Double_t *anew = new Double_t[nlmatnew];
534      Double_t *znew = new Double_t[nlmatnew];
535      Double_t *wmatnew = new Double_t[nlmatnew];
536      Int_t ind=0;
537      for (j=0; j<nlmat; j++) {
538         if (j==i) continue;
539         anew[ind] = a[j];
540         znew[ind] = z[j];
541         wmatnew[ind] = wmat[j];
542         ind++;
543      }
544      for (j=0; j<mix->GetNelements(); j++) {
545         anew[ind] = mix->GetAmixt()[j];
546         znew[ind] = mix->GetZmixt()[j];
547         wmatnew[ind] = wmat[i]*mix->GetWmixt()[j];
548         ind++;
549      }
550      Mixture(kmat, name, anew, znew, dens, nlmatnew, wmatnew);
551      delete [] anew;
552      delete [] znew;
553      delete [] wmatnew;
554      return;
555   }   
556   // Now we need to compact identical elements within the mixture
557   // First check if this happens   
558   mixnew = kFALSE;  
559   for (i=0; i<nlmat-1; i++) {
560      for (j=i+1; j<nlmat; j++) {
561         if (z[i] == z[j]) {
562            mixnew = kTRUE;
563            break;
564         }
565      }   
566      if (mixnew) break;
567   }   
568   if (mixnew) {
569      Int_t nlmatnew = 0;
570      Double_t *anew = new Double_t[nlmat];
571      Double_t *znew = new Double_t[nlmat];
572      memset(znew, 0, nlmat*sizeof(Double_t));
573      Double_t *wmatnew = new Double_t[nlmat];
574      Bool_t skipi;
575      for (i=0; i<nlmat; i++) {
576         skipi = kFALSE;
577         for (j=0; j<nlmatnew; j++) {
578            if (z[i] == z[j]) {
579               wmatnew[j] += wmat[i];
580               skipi = kTRUE;
581               break;
582            }
583         }   
584         if (skipi) continue;    
585         anew[nlmatnew] = a[i];
586         znew[nlmatnew] = z[i];
587         wmatnew[nlmatnew] = wmat[i];
588         nlmatnew++;
589      }
590      Mixture(kmat, name, anew, znew, dens, nlmatnew, wmatnew);
591      delete [] anew;
592      delete [] znew;
593      delete [] wmatnew;
594      return;     
595    }
596    gGeoManager->Mixture(name, a, z, dens, nlmat, wmat, kmat);
597
598
599 //______________________________________________________________________________ 
600 void TFluka::Medium(Int_t& kmed, const char *name, Int_t nmat, 
601                     Int_t isvol, Int_t ifield, Double_t fieldm, Double_t tmaxfd,
602                     Double_t stemax, Double_t deemax, Double_t epsil,
603                     Double_t stmin, Float_t* ubuf, Int_t nbuf) {
604   // Define a medium
605   // 
606   kmed = gGeoManager->GetListOfMedia()->GetSize()+1;
607   fMCGeo->Medium(kmed, name, nmat, isvol, ifield, fieldm, tmaxfd, stemax, deemax, 
608              epsil, stmin, ubuf, nbuf);
609
610
611 //______________________________________________________________________________ 
612 void TFluka::Medium(Int_t& kmed, const char *name, Int_t nmat, 
613                     Int_t isvol, Int_t ifield, Double_t fieldm, Double_t tmaxfd,
614                     Double_t stemax, Double_t deemax, Double_t epsil,
615                     Double_t stmin, Double_t* ubuf, Int_t nbuf) {
616   // Define a medium
617   // 
618   kmed = gGeoManager->GetListOfMedia()->GetSize()+1;
619   fMCGeo->Medium(kmed, name, nmat, isvol, ifield, fieldm, tmaxfd, stemax, deemax, 
620              epsil, stmin, ubuf, nbuf);
621
622
623 //______________________________________________________________________________ 
624 void TFluka::Matrix(Int_t& krot, Double_t thetaX, Double_t phiX, 
625                     Double_t thetaY, Double_t phiY, Double_t thetaZ,
626                     Double_t phiZ) {
627 //        
628   krot = gGeoManager->GetListOfMatrices()->GetEntriesFast();
629   fMCGeo->Matrix(krot, thetaX, phiX, thetaY, phiY, thetaZ, phiZ); 
630
631
632 //______________________________________________________________________________ 
633 void TFluka::Gstpar(Int_t itmed, const char* param, Double_t parval) {
634 //
635 //
636 //
637    Bool_t process = kFALSE;
638    Bool_t modelp  = kFALSE;
639    
640    if (strncmp(param, "DCAY",  4) == 0 ||
641        strncmp(param, "PAIR",  4) == 0 ||
642        strncmp(param, "COMP",  4) == 0 ||
643        strncmp(param, "PHOT",  4) == 0 ||
644        strncmp(param, "PFIS",  4) == 0 ||
645        strncmp(param, "DRAY",  4) == 0 ||
646        strncmp(param, "ANNI",  4) == 0 ||
647        strncmp(param, "BREM",  4) == 0 ||
648        strncmp(param, "MUNU",  4) == 0 ||
649        strncmp(param, "CKOV",  4) == 0 ||
650        strncmp(param, "HADR",  4) == 0 ||
651        strncmp(param, "LOSS",  4) == 0 ||
652        strncmp(param, "MULS",  4) == 0 ||
653        strncmp(param, "RAYL",  4) == 0) 
654    {
655        process = kTRUE;
656    } 
657    
658    if (strncmp(param, "PRIMIO_N",  8) == 0 ||
659        strncmp(param, "PRIMIO_E",  8) == 0)
660    {
661        modelp = kTRUE;
662    }
663    
664    if (process) {
665        // Process switch
666        SetProcess(param, Int_t (parval), itmed);
667    } else if (modelp) {
668        // Model parameters
669        SetModelParameter(param, parval, itmed);
670    } else {
671        // Cuts
672        SetCut(param, parval, itmed);
673    }
674    
675    
676 }    
677
678 // functions from GGEOM 
679 //_____________________________________________________________________________
680 void TFluka::Gsatt(const char *name, const char *att, Int_t val)
681
682   // Set visualisation attributes for one volume
683   char vname[5];
684   fGeom->Vname(name,vname);
685   char vatt[5];
686   fGeom->Vname(att,vatt);
687   gGeoManager->SetVolumeAttribute(vname, vatt, val);
688 }
689
690 //______________________________________________________________________________ 
691 Int_t TFluka::Gsvolu(const char *name, const char *shape, Int_t nmed,  
692                      Float_t *upar, Int_t np)  {
693 //
694     return fMCGeo->Gsvolu(name, shape, nmed, upar, np); 
695 }
696
697 //______________________________________________________________________________ 
698 Int_t TFluka::Gsvolu(const char *name, const char *shape, Int_t nmed,  
699                      Double_t *upar, Int_t np)  {
700 //
701     return fMCGeo->Gsvolu(name, shape, nmed, upar, np); 
702 }
703  
704 //______________________________________________________________________________ 
705 void TFluka::Gsdvn(const char *name, const char *mother, Int_t ndiv, 
706                    Int_t iaxis) {
707 //
708     fMCGeo->Gsdvn(name, mother, ndiv, iaxis); 
709
710
711 //______________________________________________________________________________ 
712 void TFluka::Gsdvn2(const char *name, const char *mother, Int_t ndiv, 
713                     Int_t iaxis, Double_t c0i, Int_t numed) {
714 //
715     fMCGeo->Gsdvn2(name, mother, ndiv, iaxis, c0i, numed); 
716
717
718 //______________________________________________________________________________ 
719 void TFluka::Gsdvt(const char *name, const char *mother, Double_t step, 
720                    Int_t iaxis, Int_t numed, Int_t ndvmx) {
721 //        
722     fMCGeo->Gsdvt(name, mother, step, iaxis, numed, ndvmx); 
723
724
725 //______________________________________________________________________________ 
726 void TFluka::Gsdvt2(const char *name, const char *mother, Double_t step, 
727                     Int_t iaxis, Double_t c0, Int_t numed, Int_t ndvmx) {
728 //
729     fMCGeo->Gsdvt2(name, mother, step, iaxis, c0, numed, ndvmx); 
730
731
732 //______________________________________________________________________________ 
733 void TFluka::Gsord(const char * /*name*/, Int_t /*iax*/) {
734 //
735 // Nothing to do with TGeo
736
737
738 //______________________________________________________________________________ 
739 void TFluka::Gspos(const char *name, Int_t nr, const char *mother,  
740                    Double_t x, Double_t y, Double_t z, Int_t irot,
741                    const char *konly) {
742 //
743   fMCGeo->Gspos(name, nr, mother, x, y, z, irot, konly); 
744
745
746 //______________________________________________________________________________ 
747 void TFluka::Gsposp(const char *name, Int_t nr, const char *mother,  
748                     Double_t x, Double_t y, Double_t z, Int_t irot,
749                     const char *konly, Float_t *upar, Int_t np)  {
750   //
751   fMCGeo->Gsposp(name, nr, mother, x, y, z, irot, konly, upar, np); 
752
753
754 //______________________________________________________________________________ 
755 void TFluka::Gsposp(const char *name, Int_t nr, const char *mother,  
756                     Double_t x, Double_t y, Double_t z, Int_t irot,
757                     const char *konly, Double_t *upar, Int_t np)  {
758   //
759   fMCGeo->Gsposp(name, nr, mother, x, y, z, irot, konly, upar, np); 
760
761
762 //______________________________________________________________________________ 
763 void TFluka::Gsbool(const char* /*onlyVolName*/, const char* /*manyVolName*/) {
764 //
765 // Nothing to do with TGeo
766 }
767
768 //______________________________________________________________________
769 Bool_t TFluka::GetTransformation(const TString &volumePath,TGeoHMatrix &mat)
770 {
771     // Returns the Transformation matrix between the volume specified
772     // by the path volumePath and the Top or mater volume. The format
773     // of the path volumePath is as follows (assuming ALIC is the Top volume)
774     // "/ALIC_1/DDIP_1/S05I_2/S05H_1/S05G_3". Here ALIC is the top most
775     // or master volume which has only 1 instance of. Of all of the daughter
776     // volumes of ALICE, DDIP volume copy #1 is indicated. Similarly for
777     // the daughter volume of DDIP is S05I copy #2 and so on.
778     // Inputs:
779     //   TString& volumePath  The volume path to the specific volume
780     //                        for which you want the matrix. Volume name
781     //                        hierarchy is separated by "/" while the
782     //                        copy number is appended using a "_".
783     // Outputs:
784     //  TGeoHMatrix &mat      A matrix with its values set to those
785     //                        appropriate to the Local to Master transformation
786     // Return:
787     //   A logical value if kFALSE then an error occurred and no change to
788     //   mat was made.
789
790    // We have to preserve the modeler state
791    return fMCGeo->GetTransformation(volumePath, mat);
792 }   
793    
794 //______________________________________________________________________
795 Bool_t TFluka::GetShape(const TString &volumePath,TString &shapeType,
796                         TArrayD &par)
797 {
798     // Returns the shape and its parameters for the volume specified
799     // by volumeName.
800     // Inputs:
801     //   TString& volumeName  The volume name
802     // Outputs:
803     //   TString &shapeType   Shape type
804     //   TArrayD &par         A TArrayD of parameters with all of the
805     //                        parameters of the specified shape.
806     // Return:
807     //   A logical indicating whether there was an error in getting this
808     //   information
809    return fMCGeo->GetShape(volumePath, shapeType, par);
810 }
811    
812 //______________________________________________________________________
813 Bool_t TFluka::GetMaterial(const TString &volumeName,
814                             TString &name,Int_t &imat,
815                             Double_t &a,Double_t &z,Double_t &dens,
816                             Double_t &radl,Double_t &inter,TArrayD &par)
817 {
818     // Returns the Material and its parameters for the volume specified
819     // by volumeName.
820     // Note, Geant3 stores and uses mixtures as an element with an effective
821     // Z and A. Consequently, if the parameter Z is not integer, then
822     // this material represents some sort of mixture.
823     // Inputs:
824     //   TString& volumeName  The volume name
825     // Outputs:
826     //   TSrting   &name       Material name
827     //   Int_t     &imat       Material index number
828     //   Double_t  &a          Average Atomic mass of material
829     //   Double_t  &z          Average Atomic number of material
830     //   Double_t  &dens       Density of material [g/cm^3]
831     //   Double_t  &radl       Average radiation length of material [cm]
832     //   Double_t  &inter      Average interaction length of material [cm]
833     //   TArrayD   &par        A TArrayD of user defined parameters.
834     // Return:
835     //   kTRUE if no errors
836    return fMCGeo->GetMaterial(volumeName,name,imat,a,z,dens,radl,inter,par);
837 }
838
839 //______________________________________________________________________
840 Bool_t TFluka::GetMedium(const TString &volumeName,TString &name,
841                          Int_t &imed,Int_t &nmat,Int_t &isvol,Int_t &ifield,
842                          Double_t &fieldm,Double_t &tmaxfd,Double_t &stemax,
843                          Double_t &deemax,Double_t &epsil, Double_t &stmin,
844                          TArrayD &par)
845 {
846     // Returns the Medium and its parameters for the volume specified
847     // by volumeName.
848     // Inputs:
849     //   TString& volumeName  The volume name.
850     // Outputs:
851     //   TString  &name       Medium name
852     //   Int_t    &nmat       Material number defined for this medium
853     //   Int_t    &imed       The medium index number
854     //   Int_t    &isvol      volume number defined for this medium
855     //   Int_t    &iflield    Magnetic field flag
856     //   Double_t &fieldm     Magnetic field strength
857     //   Double_t &tmaxfd     Maximum angle of deflection per step
858     //   Double_t &stemax     Maximum step size
859     //   Double_t &deemax     Maximum fraction of energy allowed to be lost
860     //                        to continuous process.
861     //   Double_t &epsil      Boundary crossing precision
862     //   Double_t &stmin      Minimum step size allowed
863     //   TArrayD  &par        A TArrayD of user parameters with all of the
864     //                        parameters of the specified medium.
865     // Return:
866     //   kTRUE if there where no errors
867    return fMCGeo->GetMedium(volumeName,name,imed,nmat,isvol,ifield,fieldm,tmaxfd,stemax,deemax,epsil,stmin,par);
868 }         
869
870 //______________________________________________________________________________ 
871 void TFluka::SetCerenkov(Int_t itmed, Int_t npckov, Float_t* ppckov,
872                          Float_t* absco, Float_t* effic, Float_t* rindex) {
873 //
874 // Set Cerenkov properties for medium itmed
875 //
876 // npckov: number of sampling points
877 // ppckov: energy values
878 // absco:  absorption length
879 // effic:  quantum efficiency
880 // rindex: refraction index
881 //
882 //
883 //  
884 //  Create object holding Cerenkov properties
885 //  
886     TFlukaCerenkov* cerenkovProperties = new TFlukaCerenkov(npckov, ppckov, absco, effic, rindex);
887 //
888 //  Pass object to medium
889     TGeoMedium* medium = gGeoManager->GetMedium(itmed);
890     medium->SetCerenkovProperties(cerenkovProperties);
891 }  
892
893 void TFluka::SetCerenkov(Int_t itmed, Int_t npckov, Float_t* ppckov,
894                          Float_t* absco, Float_t* effic, Float_t* rindex, Float_t* rfl) {
895 //
896 // Set Cerenkov properties for medium itmed
897 //
898 // npckov: number of sampling points
899 // ppckov: energy values
900 // absco:  absorption length
901 // effic:  quantum efficiency
902 // rindex: refraction index
903 // rfl:    reflectivity for boundary to medium itmed
904 //
905 //  
906 //  Create object holding Cerenkov properties
907 //  
908     TFlukaCerenkov* cerenkovProperties = new TFlukaCerenkov(npckov, ppckov, absco, effic, rindex, rfl);
909 //
910 //  Pass object to medium
911     TGeoMedium* medium = gGeoManager->GetMedium(itmed);
912     medium->SetCerenkovProperties(cerenkovProperties);
913 }  
914
915
916 //______________________________________________________________________________ 
917 void TFluka::SetCerenkov(Int_t /*itmed*/, Int_t /*npckov*/, Double_t * /*ppckov*/,
918                          Double_t * /*absco*/, Double_t * /*effic*/, Double_t * /*rindex*/) {
919 //
920 //  Double_t version not implemented
921 }  
922
923 void TFluka::SetCerenkov(Int_t /*itmed*/, Int_t /*npckov*/, Double_t* /*ppckov*/,
924                          Double_t* /*absco*/, Double_t* /*effic*/, Double_t* /*rindex*/, Double_t* /*rfl*/) {
925 //
926 // //  Double_t version not implemented
927 }
928
929 // Euclid
930 //______________________________________________________________________________ 
931 void TFluka::WriteEuclid(const char* /*fileName*/, const char* /*topVol*/, 
932                           Int_t /*number*/, Int_t /*nlevel*/) {
933 //
934 // Not with TGeo
935    Warning("WriteEuclid", "Not implemented !");
936
937
938
939
940 //_____________________________________________________________________________
941 // methods needed by the stepping
942 //____________________________________________________________________________ 
943
944 Int_t TFluka::GetMedium() const {
945 //
946 //  Get the medium number for the current fluka region
947 //
948     return fGeom->GetMedium(); // this I need to check due to remapping !!!
949 }
950
951 //____________________________________________________________________________ 
952 Int_t TFluka::GetDummyRegion() const
953 {
954 // Returns index of the dummy region.
955    return fGeom->GetDummyRegion();
956 }   
957
958 //____________________________________________________________________________ 
959 Int_t TFluka::GetDummyLattice() const
960 {
961 // Returns index of the dummy lattice.
962    return fGeom->GetDummyLattice();
963 }   
964
965 //____________________________________________________________________________ 
966 // particle table usage
967 // ID <--> PDG transformations
968 //_____________________________________________________________________________
969 Int_t TFluka::IdFromPDG(Int_t pdg) const 
970 {
971     //
972     // Return Fluka code from PDG and pseudo ENDF code
973     
974     // Catch the feedback photons
975     if (pdg == 50000051) return (kFLUKAoptical);
976     // MCIHAD() goes from pdg to fluka internal.
977     Int_t intfluka = mcihad(pdg);
978     // KPTOIP array goes from internal to official
979     return GetFlukaKPTOIP(intfluka);
980 }
981
982 //______________________________________________________________________________ 
983 Int_t TFluka::PDGFromId(Int_t id) const 
984 {
985   //
986   // Return PDG code and pseudo ENDF code from Fluka code
987   //                      Alpha     He3       Triton    Deuteron  gen. ion  opt. photon   
988     Int_t idSpecial[6] = {10020040, 10020030, 10010030, 10010020, 10000000, 50000050};
989   // IPTOKP array goes from official to internal
990
991     if (id == kFLUKAoptical) {
992 // Cerenkov photon
993 //        if (fVerbosityLevel >= 3)
994 //            printf("\n PDGFromId: Cerenkov Photon \n");
995         return  50000050;
996     }
997 // Error id    
998     if (id == 0 || id < kFLUKAcodemin || id > kFLUKAcodemax) {
999         if (fVerbosityLevel >= 3)
1000             printf("PDGFromId: Error id = 0\n");
1001         return -1;
1002     }
1003 // Good id    
1004     if (id > 0) {
1005         Int_t intfluka = GetFlukaIPTOKP(id);
1006         if (intfluka == 0) {
1007             if (fVerbosityLevel >= 3)
1008                 printf("PDGFromId: Error intfluka = 0: %d\n", id);
1009             return -1;
1010         } else if (intfluka < 0) {
1011             if (fVerbosityLevel >= 3)
1012                 printf("PDGFromId: Error intfluka < 0: %d\n", id);
1013             return -1;
1014         }
1015 //        if (fVerbosityLevel >= 3)
1016 //            printf("mpdgha called with %d %d \n", id, intfluka);
1017         return mpdgha(intfluka);
1018     } else {
1019         // ions and optical photons
1020         return idSpecial[id - kFLUKAcodemin];
1021     }
1022 }
1023
1024 void TFluka::StopTrack()
1025 {
1026     // Set stopping conditions
1027     // Works for photons and charged particles
1028     fStopped = kTRUE;
1029 }
1030   
1031 //_____________________________________________________________________________
1032 // methods for physics management
1033 //____________________________________________________________________________ 
1034 //
1035 // set methods
1036 //
1037
1038 void TFluka::SetProcess(const char* flagName, Int_t flagValue, Int_t imed)
1039 {
1040 //  Set process user flag for material imat
1041 //
1042 //    
1043 //  Update if already in the list
1044 //
1045     TIter next(fUserConfig);
1046     TFlukaConfigOption* proc;
1047     while((proc = (TFlukaConfigOption*)next()))
1048     { 
1049         if (proc->Medium() == imed) {
1050             proc->SetProcess(flagName, flagValue);
1051             return;
1052         }
1053     }
1054     proc = new TFlukaConfigOption(imed);
1055     proc->SetProcess(flagName, flagValue);
1056     fUserConfig->Add(proc);
1057 }
1058
1059 //______________________________________________________________________________ 
1060 Bool_t TFluka::SetProcess(const char* flagName, Int_t flagValue)
1061 {
1062 //  Set process user flag 
1063 //
1064 //    
1065     SetProcess(flagName, flagValue, -1);
1066     return kTRUE;  
1067 }
1068
1069 //______________________________________________________________________________ 
1070 void TFluka::SetCut(const char* cutName, Double_t cutValue, Int_t imed)
1071 {
1072 // Set user cut value for material imed
1073 //
1074     TIter next(fUserConfig);
1075     TFlukaConfigOption* proc;
1076     while((proc = (TFlukaConfigOption*)next()))
1077     { 
1078         if (proc->Medium() == imed) {
1079             proc->SetCut(cutName, cutValue);
1080             return;
1081         }
1082     }
1083
1084     proc = new TFlukaConfigOption(imed);
1085     proc->SetCut(cutName, cutValue);
1086     fUserConfig->Add(proc);
1087 }
1088
1089
1090 //______________________________________________________________________________ 
1091 void TFluka::SetModelParameter(const char* parName, Double_t parValue, Int_t imed)
1092 {
1093 // Set model parameter for material imed
1094 //
1095     TIter next(fUserConfig);
1096     TFlukaConfigOption* proc;
1097     while((proc = (TFlukaConfigOption*)next()))
1098     { 
1099         if (proc->Medium() == imed) {
1100             proc->SetModelParameter(parName, parValue);
1101             return;
1102         }
1103     }
1104
1105     proc = new TFlukaConfigOption(imed);
1106     proc->SetModelParameter(parName, parValue);
1107     fUserConfig->Add(proc);
1108 }
1109
1110 //______________________________________________________________________________ 
1111 Bool_t TFluka::SetCut(const char* cutName, Double_t cutValue)
1112 {
1113 // Set user cut value 
1114 //
1115 //    
1116     SetCut(cutName, cutValue, -1);
1117     return kTRUE;
1118 }
1119
1120
1121 void TFluka::SetUserScoring(const char* option, const char* sdum, Int_t npr, char* outfile, Float_t* what)
1122 {
1123 //
1124 // Adds a user scoring option to the list
1125 //
1126     TFlukaScoringOption* opt = new TFlukaScoringOption(option, sdum, npr,outfile,what);
1127     fUserScore->Add(opt);
1128 }
1129 //______________________________________________________________________________
1130 void TFluka::SetUserScoring(const char* option, const char* sdum, Int_t npr, char* outfile, Float_t* what, 
1131                             const char* det1, const char* det2, const char* det3)
1132 {
1133 //
1134 // Adds a user scoring option to the list
1135 //
1136     TFlukaScoringOption* opt = new TFlukaScoringOption(option, sdum, npr, outfile, what, det1, det2, det3);
1137     fUserScore->Add(opt);
1138 }
1139
1140 //______________________________________________________________________________ 
1141 Double_t TFluka::Xsec(char*, Double_t, Int_t, Int_t)
1142 {
1143   Warning("Xsec", "Not yet implemented.!\n"); return -1.;
1144 }
1145
1146
1147 //______________________________________________________________________________ 
1148 void TFluka::InitPhysics()
1149 {
1150 //
1151 // Physics initialisation with preparation of FLUKA input cards
1152 //
1153 // Construct file names
1154     FILE *pFlukaVmcCoreInp, *pFlukaVmcFlukaMat, *pFlukaVmcInp;
1155     TString sFlukaVmcCoreInp = getenv("ALICE_ROOT");
1156     sFlukaVmcCoreInp +="/TFluka/input/";
1157     TString sFlukaVmcTmp = "flukaMat.inp";
1158     TString sFlukaVmcInp = GetInputFileName();
1159     sFlukaVmcCoreInp += GetCoreInputFileName();
1160     
1161 // Open files 
1162     if ((pFlukaVmcCoreInp = fopen(sFlukaVmcCoreInp.Data(),"r")) == NULL) {
1163         Warning("InitPhysics", "\nCannot open file %s\n",sFlukaVmcCoreInp.Data());
1164         exit(1);
1165     }
1166     if ((pFlukaVmcFlukaMat = fopen(sFlukaVmcTmp.Data(),"r")) == NULL) {
1167         Warning("InitPhysics", "\nCannot open file %s\n",sFlukaVmcTmp.Data());
1168         exit(1);
1169     }
1170     if ((pFlukaVmcInp = fopen(sFlukaVmcInp.Data(),"w")) == NULL) {
1171         Warning("InitPhysics", "\nCannot open file %s\n",sFlukaVmcInp.Data());
1172         exit(1);
1173     }
1174
1175 // Copy core input file 
1176     Char_t sLine[255];
1177     Float_t fEventsPerRun;
1178     
1179     while ((fgets(sLine,255,pFlukaVmcCoreInp)) != NULL) {
1180         if (strncmp(sLine,"GEOEND",6) != 0)
1181             fprintf(pFlukaVmcInp,"%s",sLine); // copy until GEOEND card
1182         else {
1183             fprintf(pFlukaVmcInp,"GEOEND\n");   // add GEOEND card
1184             goto flukamat;
1185         }
1186     } // end of while until GEOEND card
1187     
1188
1189  flukamat:
1190     while ((fgets(sLine,255,pFlukaVmcFlukaMat)) != NULL) { // copy flukaMat.inp file
1191         fprintf(pFlukaVmcInp,"%s\n",sLine);
1192     }
1193     
1194     while ((fgets(sLine,255,pFlukaVmcCoreInp)) != NULL) { 
1195         if (strncmp(sLine,"START",5) != 0)
1196             fprintf(pFlukaVmcInp,"%s\n",sLine);
1197         else {
1198             sscanf(sLine+10,"%10f",&fEventsPerRun);
1199             goto fin;
1200         }
1201     } //end of while until START card
1202     
1203  fin:
1204
1205     
1206 // Pass information to configuration objects
1207     
1208     Float_t fLastMaterial = fGeom->GetLastMaterialIndex();
1209     TFlukaConfigOption::SetStaticInfo(pFlukaVmcInp, 3, fLastMaterial, fGeom);
1210     
1211     TIter next(fUserConfig);
1212     TFlukaConfigOption* proc;
1213     while((proc = dynamic_cast<TFlukaConfigOption*> (next()))) proc->WriteFlukaInputCards();
1214 //
1215 // Process Fluka specific scoring options
1216 //
1217     TFlukaScoringOption::SetStaticInfo(pFlukaVmcInp, fGeom);
1218     Float_t loginp        = 49.0;
1219     Int_t inp             = 0;
1220     Int_t nscore          = fUserScore->GetEntries();
1221     
1222     TFlukaScoringOption *mopo = 0;
1223     TFlukaScoringOption *mopi = 0;
1224
1225     for (Int_t isc = 0; isc < nscore; isc++) 
1226     {
1227         mopo = dynamic_cast<TFlukaScoringOption*> (fUserScore->At(isc));
1228         char*    fileName = mopo->GetFileName();
1229         Int_t    size     = strlen(fileName);
1230         Float_t  lun      = -1.;
1231 //
1232 // Check if new output file has to be opened
1233         for (Int_t isci = 0; isci < isc; isci++) {
1234
1235         
1236             mopi = dynamic_cast<TFlukaScoringOption*> (fUserScore->At(isci));
1237             if(strncmp(mopi->GetFileName(), fileName, size)==0) {
1238                 //
1239                 // No, the file already exists
1240                 lun = mopi->GetLun();
1241                 mopo->SetLun(lun);
1242                 break;
1243             }
1244         } // inner loop
1245
1246         if (lun == -1.) {
1247             // Open new output file
1248             inp++;
1249             mopo->SetLun(loginp + inp);
1250             mopo->WriteOpenFlukaFile();
1251         }
1252         mopo->WriteFlukaInputCards();
1253     }
1254
1255 // Add RANDOMIZ card
1256     fprintf(pFlukaVmcInp,"RANDOMIZ  %10.1f%10.0f\n", 1., Float_t(gRandom->GetSeed()));
1257 // Add START and STOP card
1258     fprintf(pFlukaVmcInp,"START     %10.1f\n",fEventsPerRun);
1259     fprintf(pFlukaVmcInp,"STOP      \n");
1260    
1261   
1262 // Close files
1263    fclose(pFlukaVmcCoreInp);
1264    fclose(pFlukaVmcFlukaMat);
1265    fclose(pFlukaVmcInp);
1266
1267
1268 //
1269 // Initialisation needed for Cerenkov photon production and transport
1270     TObjArray *matList = GetFlukaMaterials();
1271     Int_t nmaterial =  matList->GetEntriesFast();
1272     fMaterials = new Int_t[nmaterial+3];
1273     
1274     for (Int_t im = 0; im < nmaterial; im++)
1275     {
1276         TGeoMaterial* material = dynamic_cast<TGeoMaterial*> (matList->At(im));
1277         Int_t idmat = material->GetIndex();
1278         fMaterials[idmat] = im;
1279     }
1280 } // end of InitPhysics
1281
1282
1283 //______________________________________________________________________________ 
1284 void TFluka::SetMaxStep(Double_t step)
1285 {
1286 // Set the maximum step size
1287 //    if (step > 1.e4) return;
1288     
1289 //    Int_t mreg=0, latt=0;
1290 //    fGeom->GetCurrentRegion(mreg, latt);
1291     Int_t mreg = fGeom->GetCurrentRegion();
1292     STEPSZ.stepmx[mreg - 1] = step;
1293 }
1294
1295
1296 Double_t TFluka::MaxStep() const
1297 {
1298 // Return the maximum for current medium
1299     Int_t mreg, latt;
1300     fGeom->GetCurrentRegion(mreg, latt);
1301     return (STEPSZ.stepmx[mreg - 1]);
1302 }
1303
1304 //______________________________________________________________________________ 
1305 void TFluka::SetMaxNStep(Int_t)
1306 {
1307 // SetMaxNStep is dummy procedure in TFluka !
1308   if (fVerbosityLevel >=3)
1309   cout << "SetMaxNStep is dummy procedure in TFluka !" << endl;
1310 }
1311
1312 //______________________________________________________________________________ 
1313 void TFluka::SetUserDecay(Int_t)
1314 {
1315 // SetUserDecay is dummy procedure in TFluka !
1316   if (fVerbosityLevel >=3)
1317   cout << "SetUserDecay is dummy procedure in TFluka !" << endl;
1318 }
1319
1320 //
1321 // dynamic properties
1322 //
1323 //______________________________________________________________________________ 
1324 void TFluka::TrackPosition(TLorentzVector& position) const
1325 {
1326 // Return the current position in the master reference frame of the
1327 // track being transported
1328 // TRACKR.atrack = age of the particle
1329 // TRACKR.xtrack = x-position of the last point
1330 // TRACKR.ytrack = y-position of the last point
1331 // TRACKR.ztrack = z-position of the last point
1332   FlukaCallerCode_t caller = GetCaller();
1333   if (caller == kENDRAW    || caller == kUSDRAW || 
1334       caller == kBXExiting || caller == kBXEntering || 
1335       caller == kUSTCKV) { 
1336     position.SetX(GetXsco());
1337     position.SetY(GetYsco());
1338     position.SetZ(GetZsco());
1339     position.SetT(TRACKR.atrack);
1340   }
1341   else if (caller == kMGDRAW) {
1342       Int_t i = -1;
1343       if ((i = fPrimaryElectronIndex) > -1) {
1344           // Primary Electron Ionisation
1345           Double_t x, y, z;
1346           GetPrimaryElectronPosition(i, x, y, z);
1347           position.SetX(x);
1348           position.SetY(y);
1349           position.SetZ(z);
1350           position.SetT(TRACKR.atrack);
1351       } else {
1352           position.SetX(TRACKR.xtrack[TRACKR.ntrack]);
1353           position.SetY(TRACKR.ytrack[TRACKR.ntrack]);
1354           position.SetZ(TRACKR.ztrack[TRACKR.ntrack]);
1355           position.SetT(TRACKR.atrack);
1356       }
1357   }
1358   else if (caller == kSODRAW) { 
1359     position.SetX(TRACKR.xtrack[TRACKR.ntrack]);
1360     position.SetY(TRACKR.ytrack[TRACKR.ntrack]);
1361     position.SetZ(TRACKR.ztrack[TRACKR.ntrack]);
1362     position.SetT(0);
1363   } else if (caller == kMGResumedTrack) { 
1364     position.SetX(TRACKR.spausr[0]);
1365     position.SetY(TRACKR.spausr[1]);
1366     position.SetZ(TRACKR.spausr[2]);
1367     position.SetT(TRACKR.spausr[3]);
1368   }
1369   else
1370     Warning("TrackPosition","position not available");
1371 }
1372
1373 //______________________________________________________________________________ 
1374 void TFluka::TrackPosition(Double_t& x, Double_t& y, Double_t& z) const
1375 {
1376 // Return the current position in the master reference frame of the
1377 // track being transported
1378 // TRACKR.atrack = age of the particle
1379 // TRACKR.xtrack = x-position of the last point
1380 // TRACKR.ytrack = y-position of the last point
1381 // TRACKR.ztrack = z-position of the last point
1382   FlukaCallerCode_t caller = GetCaller();
1383   if (caller == kENDRAW    || caller == kUSDRAW || 
1384       caller == kBXExiting || caller == kBXEntering || 
1385       caller == kUSTCKV) { 
1386       x = GetXsco();
1387       y = GetYsco();
1388       z = GetZsco();
1389   }
1390   else if (caller == kMGDRAW || caller == kSODRAW) { 
1391       Int_t i = -1;
1392       if ((i = fPrimaryElectronIndex) > -1) {
1393           GetPrimaryElectronPosition(i, x, y, z);
1394       } else {
1395           x = TRACKR.xtrack[TRACKR.ntrack];
1396           y = TRACKR.ytrack[TRACKR.ntrack];
1397           z = TRACKR.ztrack[TRACKR.ntrack];
1398       }
1399   }
1400   else if (caller == kMGResumedTrack) {
1401     x = TRACKR.spausr[0];
1402     y = TRACKR.spausr[1];
1403     z = TRACKR.spausr[2];
1404   }
1405   else
1406     Warning("TrackPosition","position not available");
1407 }
1408
1409 //______________________________________________________________________________ 
1410 void TFluka::TrackMomentum(TLorentzVector& momentum) const
1411 {
1412 // Return the direction and the momentum (GeV/c) of the track
1413 // currently being transported
1414 // TRACKR.ptrack = momentum of the particle (not always defined, if
1415 //               < 0 must be obtained from etrack) 
1416 // TRACKR.cx,y,ztrck = direction cosines of the current particle
1417 // TRACKR.etrack = total energy of the particle
1418 // TRACKR.jtrack = identity number of the particle
1419 // PAPROP.am[TRACKR.jtrack] = particle mass in gev
1420   FlukaCallerCode_t  caller = GetCaller();
1421   FlukaProcessCode_t icode  = GetIcode();
1422   
1423   if (caller != kEEDRAW && caller != kMGResumedTrack && 
1424       (caller != kENDRAW || (icode != kEMFSCOstopping1 && icode != kEMFSCOstopping2))) {
1425     if (TRACKR.ptrack >= 0) {
1426       momentum.SetPx(TRACKR.ptrack*TRACKR.cxtrck);
1427       momentum.SetPy(TRACKR.ptrack*TRACKR.cytrck);
1428       momentum.SetPz(TRACKR.ptrack*TRACKR.cztrck);
1429       momentum.SetE(TRACKR.etrack);
1430       return;
1431     }
1432     else {
1433       Double_t p = sqrt(TRACKR.etrack * TRACKR.etrack - ParticleMassFPC(TRACKR.jtrack) * ParticleMassFPC(TRACKR.jtrack));
1434       momentum.SetPx(p*TRACKR.cxtrck);
1435       momentum.SetPy(p*TRACKR.cytrck);
1436       momentum.SetPz(p*TRACKR.cztrck);
1437       momentum.SetE(TRACKR.etrack);
1438       return;
1439     }
1440   } else if  (caller == kMGResumedTrack) {
1441     momentum.SetPx(TRACKR.spausr[4]);
1442     momentum.SetPy(TRACKR.spausr[5]);
1443     momentum.SetPz(TRACKR.spausr[6]);
1444     momentum.SetE (TRACKR.spausr[7]);
1445     return;
1446   } else if (caller == kENDRAW && (icode == kEMFSCOstopping1 || icode == kEMFSCOstopping2)) {
1447       momentum.SetPx(0.);
1448       momentum.SetPy(0.);
1449       momentum.SetPz(0.);
1450       momentum.SetE(TrackMass());
1451   }
1452   else
1453     Warning("TrackMomentum","momentum not available");
1454 }
1455
1456 //______________________________________________________________________________ 
1457 void TFluka::TrackMomentum(Double_t& px, Double_t& py, Double_t& pz, Double_t& e) const
1458 {
1459 // Return the direction and the momentum (GeV/c) of the track
1460 // currently being transported
1461 // TRACKR.ptrack = momentum of the particle (not always defined, if
1462 //               < 0 must be obtained from etrack) 
1463 // TRACKR.cx,y,ztrck = direction cosines of the current particle
1464 // TRACKR.etrack = total energy of the particle
1465 // TRACKR.jtrack = identity number of the particle
1466 // PAPROP.am[TRACKR.jtrack] = particle mass in gev
1467   FlukaCallerCode_t   caller = GetCaller();
1468   FlukaProcessCode_t  icode  = GetIcode();
1469   if (caller != kEEDRAW && caller != kMGResumedTrack && 
1470       (caller != kENDRAW || (icode != kEMFSCOstopping1 && icode != kEMFSCOstopping2))) {
1471     if (TRACKR.ptrack >= 0) {
1472       px = TRACKR.ptrack*TRACKR.cxtrck;
1473       py = TRACKR.ptrack*TRACKR.cytrck;
1474       pz = TRACKR.ptrack*TRACKR.cztrck;
1475       e  = TRACKR.etrack;
1476       return;
1477     }
1478     else {
1479       Double_t p = sqrt(TRACKR.etrack * TRACKR.etrack - ParticleMassFPC(TRACKR.jtrack) *  ParticleMassFPC(TRACKR.jtrack));
1480       px = p*TRACKR.cxtrck;
1481       py = p*TRACKR.cytrck;
1482       pz = p*TRACKR.cztrck;
1483       e  = TRACKR.etrack;
1484       return;
1485     }
1486   } else if (caller == kMGResumedTrack) {
1487       px = TRACKR.spausr[4];
1488       py = TRACKR.spausr[5];
1489       pz = TRACKR.spausr[6];
1490       e  = TRACKR.spausr[7];
1491       return;
1492   } else if (caller == kENDRAW && (icode == kEMFSCOstopping1 || icode == kEMFSCOstopping2)) {
1493       px = 0.;
1494       py = 0.;
1495       pz = 0.;
1496       e  = TrackMass();
1497   }
1498   else
1499     Warning("TrackMomentum","momentum not available");
1500 }
1501
1502 //______________________________________________________________________________ 
1503 Double_t TFluka::TrackStep() const
1504 {
1505 // Return the length in centimeters of the current step
1506 // TRACKR.ctrack = total curved path
1507   FlukaCallerCode_t caller = GetCaller();
1508   if (caller == kBXEntering || caller == kBXExiting || 
1509       caller == kENDRAW     || caller == kUSDRAW || 
1510       caller == kUSTCKV     || caller == kMGResumedTrack)
1511     return 0.0;
1512   else if (caller == kMGDRAW)
1513     return TRACKR.ctrack;
1514   else {
1515     Warning("TrackStep", "track step not available");
1516     return 0.0;
1517   }  
1518 }
1519
1520 //______________________________________________________________________________ 
1521 Double_t TFluka::TrackLength() const
1522 {
1523 // TRACKR.cmtrck = cumulative curved path since particle birth
1524   FlukaCallerCode_t caller = GetCaller();
1525   if (caller == kBXEntering || caller == kBXExiting || 
1526       caller == kENDRAW || caller == kUSDRAW || caller == kMGDRAW || 
1527       caller == kUSTCKV) 
1528     return TRACKR.cmtrck;
1529   else if (caller == kMGResumedTrack) 
1530     return TRACKR.spausr[8];
1531   else {
1532     Warning("TrackLength", "track length not available");
1533     return 0.0;
1534   } 
1535 }
1536
1537 //______________________________________________________________________________ 
1538 Double_t TFluka::TrackTime() const
1539 {
1540 // Return the current time of flight of the track being transported
1541 // TRACKR.atrack = age of the particle
1542   FlukaCallerCode_t caller = GetCaller();
1543   if (caller == kBXEntering || caller == kBXExiting || 
1544       caller == kENDRAW     || caller == kUSDRAW    || caller == kMGDRAW || 
1545       caller == kUSTCKV)
1546     return TRACKR.atrack;
1547   else if (caller == kMGResumedTrack)
1548     return TRACKR.spausr[3];
1549   else {
1550     Warning("TrackTime", "track time not available");
1551     return 0.0;
1552   }   
1553 }
1554
1555 //______________________________________________________________________________ 
1556 Double_t TFluka::Edep() const
1557 {
1558 // Energy deposition
1559 // if TRACKR.ntrack = 0, TRACKR.mtrack = 0:
1560 // -->local energy deposition (the value and the point are not recorded in TRACKR)
1561 //    but in the variable "rull" of the procedure "endraw.cxx"
1562 // if TRACKR.ntrack > 0, TRACKR.mtrack = 0:
1563 // -->no energy loss along the track
1564 // if TRACKR.ntrack > 0, TRACKR.mtrack > 0:
1565 // -->energy loss distributed along the track
1566 // TRACKR.dtrack = energy deposition of the jth deposition event
1567
1568   // If coming from bxdraw we have 2 steps of 0 length and 0 edep
1569   // If coming from usdraw we just signal particle production - no edep
1570   // If just first time after resuming, no edep for the primary
1571   FlukaCallerCode_t caller = GetCaller();
1572     
1573   if (caller == kBXExiting || caller == kBXEntering || 
1574       caller == kUSDRAW    || caller == kMGResumedTrack) return 0.0;
1575   Double_t sum = 0;
1576   Int_t i = -1;
1577   
1578   // Material with primary ionisation activated but number of primary electrons nprim = 0
1579   if (fPrimaryElectronIndex == -2) return 0.0;
1580   // nprim > 0
1581   if ((i = fPrimaryElectronIndex) > -1) {
1582       // Primary ionisation
1583       sum = GetPrimaryElectronKineticEnergy(i);
1584       if (sum > 100.) {
1585           printf("edep > 100. %d %d %f \n", i, ALLDLT.nalldl, sum);
1586       }
1587       return sum;
1588   } else {
1589       // Normal ionisation
1590       if (TRACKR.mtrack > 1) printf("Edep: %6d\n", TRACKR.mtrack);
1591       
1592       for ( Int_t j=0;j<TRACKR.mtrack;j++) {
1593           sum +=TRACKR.dtrack[j];  
1594       }
1595       if (TRACKR.ntrack == 0 && TRACKR.mtrack == 0)
1596           return fRull + sum;
1597       else {
1598           return sum;
1599       }
1600   }
1601 }
1602
1603 //______________________________________________________________________________ 
1604 Int_t TFluka::CorrectFlukaId() const
1605 {
1606    // since we don't put photons and e- created bellow transport cut on the vmc stack
1607    // and there is a call to endraw for energy deposition for each of them
1608    // and they have the track number of their parent, but different identity (pdg)
1609    // so we want to assign also their parent identity.
1610    if( (IsTrackStop() )
1611         && TRACKR.ispusr[mkbmx2 - 4] == TRACKR.ispusr[mkbmx2 - 1]
1612         && TRACKR.jtrack != TRACKR.ispusr[mkbmx2 - 3] ) {
1613       if (fVerbosityLevel >=3)
1614          cout << "CorrectFlukaId() for icode=" << GetIcode()
1615                << " track=" << TRACKR.ispusr[mkbmx2 - 1]
1616                << " current PDG=" << PDGFromId(TRACKR.jtrack)
1617                << " assign parent PDG=" << PDGFromId(TRACKR.ispusr[mkbmx2 - 3]) << endl;
1618       return TRACKR.ispusr[mkbmx2 - 3]; // assign parent identity
1619    }
1620    return TRACKR.jtrack;
1621 }
1622
1623
1624 //______________________________________________________________________________ 
1625 Int_t TFluka::TrackPid() const
1626 {
1627 // Return the id of the particle transported
1628 // TRACKR.jtrack = identity number of the particle
1629   FlukaCallerCode_t caller = GetCaller();
1630   if (caller != kEEDRAW) {
1631      return PDGFromId( CorrectFlukaId() );
1632   }
1633   else
1634     return -1000;
1635 }
1636
1637 //______________________________________________________________________________ 
1638 Double_t TFluka::TrackCharge() const
1639 {
1640 // Return charge of the track currently transported
1641 // PAPROP.ichrge = electric charge of the particle
1642 // TRACKR.jtrack = identity number of the particle
1643   FlukaCallerCode_t caller = GetCaller();
1644   if (caller != kEEDRAW) 
1645      return PAPROP.ichrge[CorrectFlukaId()+6];
1646   else
1647     return -1000.0;
1648 }
1649
1650 //______________________________________________________________________________ 
1651 Double_t TFluka::TrackMass() const
1652 {
1653 // PAPROP.am = particle mass in GeV
1654 // TRACKR.jtrack = identity number of the particle
1655   FlukaCallerCode_t caller = GetCaller();
1656   if (caller != kEEDRAW)
1657      return PAPROP.am[CorrectFlukaId()+6];
1658   else
1659     return -1000.0;
1660 }
1661
1662 //______________________________________________________________________________ 
1663 Double_t TFluka::Etot() const
1664 {
1665 // TRACKR.etrack = total energy of the particle
1666   FlukaCallerCode_t caller = GetCaller();
1667   if (caller != kEEDRAW)
1668     return TRACKR.etrack;
1669   else
1670     return -1000.0;
1671 }
1672
1673 //
1674 // track status
1675 //
1676 //______________________________________________________________________________ 
1677 Bool_t   TFluka::IsNewTrack() const
1678 {
1679 // Return true for the first call of Stepping()
1680    return fTrackIsNew;
1681 }
1682
1683 void     TFluka::SetTrackIsNew(Bool_t flag)
1684 {
1685 // Return true for the first call of Stepping()
1686    fTrackIsNew = flag;
1687
1688 }
1689
1690
1691 //______________________________________________________________________________ 
1692 Bool_t   TFluka::IsTrackInside() const
1693 {
1694 // True if the track is not at the boundary of the current volume
1695 // In Fluka a step is always inside one kind of material
1696 // If the step would go behind the region of one material,
1697 // it will be shortened to reach only the boundary.
1698 // Therefore IsTrackInside() is always true.
1699   FlukaCallerCode_t caller = GetCaller();
1700   if (caller == kBXEntering || caller == kBXExiting)
1701     return 0;
1702   else
1703     return 1;
1704 }
1705
1706 //______________________________________________________________________________ 
1707 Bool_t   TFluka::IsTrackEntering() const
1708 {
1709 // True if this is the first step of the track in the current volume
1710
1711   FlukaCallerCode_t caller = GetCaller();
1712   if (caller == kBXEntering)
1713     return 1;
1714   else return 0;
1715 }
1716
1717 //______________________________________________________________________________ 
1718 Bool_t   TFluka::IsTrackExiting() const
1719 {
1720 // True if track is exiting volume
1721 //
1722   FlukaCallerCode_t caller = GetCaller();
1723   if (caller == kBXExiting)
1724     return 1;
1725   else return 0;
1726 }
1727
1728 //______________________________________________________________________________ 
1729 Bool_t   TFluka::IsTrackOut() const
1730 {
1731 // True if the track is out of the setup
1732 // means escape
1733   FlukaProcessCode_t icode = GetIcode();
1734     
1735   if (icode == kKASKADescape ||
1736       icode == kEMFSCOescape ||
1737       icode == kKASNEUescape ||
1738       icode == kKASHEAescape ||
1739       icode == kKASOPHescape) 
1740        return 1;
1741   else return 0;
1742 }
1743
1744 //______________________________________________________________________________ 
1745 Bool_t   TFluka::IsTrackDisappeared() const
1746 {
1747 // All inelastic interactions and decays
1748 // fIcode from usdraw
1749   FlukaProcessCode_t icode = GetIcode();
1750   if (icode == kKASKADinelint    || // inelastic interaction
1751       icode == kKASKADdecay      || // particle decay
1752       icode == kKASKADdray       || // delta ray generation by hadron
1753       icode == kKASKADpair       || // direct pair production
1754       icode == kKASKADbrems      || // bremsstrahlung (muon)
1755       icode == kEMFSCObrems      || // bremsstrahlung (electron)
1756       icode == kEMFSCOmoller     || // Moller scattering
1757       icode == kEMFSCObhabha     || // Bhaba scattering
1758       icode == kEMFSCOanniflight || // in-flight annihilation
1759       icode == kEMFSCOannirest   || // annihilation at rest
1760       icode == kEMFSCOpair       || // pair production
1761       icode == kEMFSCOcompton    || // Compton scattering
1762       icode == kEMFSCOphotoel    || // Photoelectric effect
1763       icode == kKASNEUhadronic   || // hadronic interaction
1764       icode == kKASHEAdray          // delta-ray
1765       ) return 1;
1766   else return 0;
1767 }
1768
1769 //______________________________________________________________________________ 
1770 Bool_t   TFluka::IsTrackStop() const
1771 {
1772 // True if the track energy has fallen below the threshold
1773 // means stopped by signal or below energy threshold
1774   FlukaProcessCode_t icode = GetIcode();
1775   if (icode == kKASKADstopping  || // stopping particle
1776       icode == kKASKADtimekill  || // time kill 
1777       icode == kEMFSCOstopping1 || // below user-defined cut-off
1778       icode == kEMFSCOstopping2 || // below user cut-off
1779       icode == kEMFSCOtimekill  || // time kill
1780       icode == kKASNEUstopping  || // neutron below threshold
1781       icode == kKASNEUtimekill  || // time kill
1782       icode == kKASHEAtimekill  || // time kill
1783       icode == kKASOPHtimekill) return 1; // time kill
1784   else return 0;
1785 }
1786
1787 //______________________________________________________________________________ 
1788 Bool_t   TFluka::IsTrackAlive() const
1789 {
1790 // means not disappeared or not out
1791   if (IsTrackDisappeared() || IsTrackOut() ) return 0;
1792   else return 1;
1793 }
1794
1795 //
1796 // secondaries
1797 //
1798
1799 //______________________________________________________________________________ 
1800 Int_t TFluka::NSecondaries() const
1801
1802 {
1803 // Number of secondary particles generated in the current step
1804 // GENSTK.np = number of secondaries except light and heavy ions
1805 // FHEAVY.npheav = number of secondaries for light and heavy secondary ions
1806     FlukaCallerCode_t caller = GetCaller();
1807     if (caller == kUSDRAW)  // valid only after usdraw
1808         return GENSTK.np + FHEAVY.npheav;
1809     else if (caller == kUSTCKV) {
1810         // Cerenkov Photon production
1811         return fNCerenkov;
1812     }
1813     return 0;
1814 } // end of NSecondaries
1815
1816 //______________________________________________________________________________ 
1817 void TFluka::GetSecondary(Int_t isec, Int_t& particleId,
1818                 TLorentzVector& position, TLorentzVector& momentum)
1819 {
1820 // Copy particles from secondary stack to vmc stack
1821 //
1822
1823     FlukaCallerCode_t caller = GetCaller();
1824     if (caller == kUSDRAW) {  // valid only after usdraw
1825         if (GENSTK.np > 0) {
1826             // Hadronic interaction
1827             if (isec >= 0 && isec < GENSTK.np) {
1828                 particleId = PDGFromId(GENSTK.kpart[isec]);
1829                 position.SetX(fXsco);
1830                 position.SetY(fYsco);
1831                 position.SetZ(fZsco);
1832                 position.SetT(TRACKR.atrack);
1833                 momentum.SetPx(GENSTK.plr[isec]*GENSTK.cxr[isec]);
1834                 momentum.SetPy(GENSTK.plr[isec]*GENSTK.cyr[isec]);
1835                 momentum.SetPz(GENSTK.plr[isec]*GENSTK.czr[isec]);
1836                 momentum.SetE(GENSTK.tki[isec] + PAPROP.am[GENSTK.kpart[isec]+6]);
1837             }
1838             else if (isec >= GENSTK.np && isec < GENSTK.np + FHEAVY.npheav) {
1839                 Int_t jsec = isec - GENSTK.np;
1840                 particleId = FHEAVY.kheavy[jsec]; // this is Fluka id !!!
1841                 position.SetX(fXsco);
1842                 position.SetY(fYsco);
1843                 position.SetZ(fZsco);
1844                 position.SetT(TRACKR.atrack);
1845                 momentum.SetPx(FHEAVY.pheavy[jsec]*FHEAVY.cxheav[jsec]);
1846                 momentum.SetPy(FHEAVY.pheavy[jsec]*FHEAVY.cyheav[jsec]);
1847                 momentum.SetPz(FHEAVY.pheavy[jsec]*FHEAVY.czheav[jsec]);
1848                 if (FHEAVY.tkheav[jsec] >= 3 && FHEAVY.tkheav[jsec] <= 6)
1849                     momentum.SetE(FHEAVY.tkheav[jsec] + PAPROP.am[jsec+6]);
1850                 else if (FHEAVY.tkheav[jsec] > 6)
1851                     momentum.SetE(FHEAVY.tkheav[jsec] + FHEAVY.amnhea[jsec]); // to be checked !!!
1852             }
1853             else
1854                 Warning("GetSecondary","isec out of range");
1855         }
1856     } else if (caller == kUSTCKV) {
1857         Int_t index = OPPHST.lstopp - isec;
1858         position.SetX(OPPHST.xoptph[index]);
1859         position.SetY(OPPHST.yoptph[index]);
1860         position.SetZ(OPPHST.zoptph[index]);
1861         position.SetT(OPPHST.agopph[index]);
1862         Double_t p = OPPHST.poptph[index];
1863         
1864         momentum.SetPx(p * OPPHST.txopph[index]);
1865         momentum.SetPy(p * OPPHST.tyopph[index]);
1866         momentum.SetPz(p * OPPHST.tzopph[index]);
1867         momentum.SetE(p);
1868     }
1869     else
1870         Warning("GetSecondary","no secondaries available");
1871     
1872 } // end of GetSecondary
1873
1874
1875 //______________________________________________________________________________ 
1876 TMCProcess TFluka::ProdProcess(Int_t) const
1877
1878 {
1879 // Name of the process that has produced the secondary particles
1880 // in the current step
1881
1882     Int_t mugamma = (TRACKR.jtrack == kFLUKAphoton || 
1883                      TRACKR.jtrack == kFLUKAmuplus ||
1884                      TRACKR.jtrack == kFLUKAmuminus);
1885     FlukaProcessCode_t icode = GetIcode();
1886
1887     if      (icode == kKASKADdecay)                                   return kPDecay;
1888     else if (icode == kKASKADpair || icode == kEMFSCOpair)            return kPPair;
1889     else if (icode == kEMFSCOcompton)                                 return kPCompton;
1890     else if (icode == kEMFSCOphotoel)                                 return kPPhotoelectric;
1891     else if (icode == kKASKADbrems      || icode == kEMFSCObrems)     return kPBrem;
1892     else if (icode == kKASKADdray       || icode == kKASHEAdray)      return kPDeltaRay;
1893     else if (icode == kEMFSCOmoller     || icode == kEMFSCObhabha)    return kPDeltaRay;
1894     else if (icode == kEMFSCOanniflight || icode == kEMFSCOannirest)  return kPAnnihilation;
1895     else if (icode == kKASKADinelint) {
1896         if (!mugamma)                                                 return kPHadronic;
1897         else if (TRACKR.jtrack == kFLUKAphoton)                       return kPPhotoFission;
1898         else                                                          return kPMuonNuclear;
1899     }
1900     else if (icode == kEMFSCOrayleigh)                                return kPRayleigh;
1901 // Fluka codes 100, 300 and 400 still to be investigasted
1902     else                                                              return kPNoProcess;
1903 }
1904
1905
1906 Int_t TFluka::StepProcesses(TArrayI &proc) const
1907 {
1908   //
1909   // Return processes active in the current step
1910   //
1911     FlukaProcessCode_t icode = GetIcode();
1912     proc.Set(1);
1913     TMCProcess iproc;
1914     switch (icode) {
1915     case kKASKADtimekill:
1916     case kEMFSCOtimekill:
1917     case kKASNEUtimekill:
1918     case kKASHEAtimekill:
1919     case kKASOPHtimekill:
1920         iproc =  kPTOFlimit;
1921         break;
1922     case kKASKADstopping:
1923     case kKASKADescape:
1924     case kEMFSCOstopping1:
1925     case kEMFSCOstopping2:
1926     case kEMFSCOescape:
1927     case kKASNEUstopping:
1928     case kKASNEUescape:
1929     case kKASHEAescape:
1930     case kKASOPHescape:
1931         iproc = kPStop;
1932         break;
1933     case kKASOPHabsorption:
1934         iproc = kPLightAbsorption;
1935         break;
1936     case kKASOPHrefraction:
1937         iproc = kPLightRefraction;
1938     case kEMSCOlocaledep : 
1939         iproc = kPPhotoelectric;
1940         break;
1941     default:
1942         iproc = ProdProcess(0);
1943     }
1944     proc[0] = iproc;
1945     return 1;
1946 }
1947 //______________________________________________________________________________ 
1948 Int_t TFluka::VolId2Mate(Int_t id) const
1949 {
1950 //
1951 // Returns the material number for a given volume ID
1952 //
1953    return fMCGeo->VolId2Mate(id);
1954 }
1955
1956 //______________________________________________________________________________ 
1957 const char* TFluka::VolName(Int_t id) const
1958 {
1959 //
1960 // Returns the volume name for a given volume ID
1961 //
1962    return fMCGeo->VolName(id);
1963 }
1964
1965 //______________________________________________________________________________ 
1966 Int_t TFluka::VolId(const Text_t* volName) const
1967 {
1968 //
1969 // Converts from volume name to volume ID.
1970 // Time consuming. (Only used during set-up)
1971 // Could be replaced by hash-table
1972 //
1973     char sname[20];
1974     Int_t len;
1975     strncpy(sname, volName, len = strlen(volName));
1976     sname[len] = 0;
1977     while (sname[len - 1] == ' ') sname[--len] = 0;
1978     return fMCGeo->VolId(sname);
1979 }
1980
1981 //______________________________________________________________________________ 
1982 Int_t TFluka::CurrentVolID(Int_t& copyNo) const
1983 {
1984 //
1985 // Return the logical id and copy number corresponding to the current fluka region
1986 //
1987   if (gGeoManager->IsOutside()) return 0;
1988   TGeoNode *node = gGeoManager->GetCurrentNode();
1989   copyNo = node->GetNumber();
1990   Int_t id = node->GetVolume()->GetNumber();
1991   return id;
1992
1993
1994 //______________________________________________________________________________ 
1995 Int_t TFluka::CurrentVolOffID(Int_t off, Int_t& copyNo) const
1996 {
1997 //
1998 // Return the logical id and copy number of off'th mother 
1999 // corresponding to the current fluka region
2000 //
2001   if (off<0 || off>gGeoManager->GetLevel()) return 0;
2002   if (off==0) return CurrentVolID(copyNo);
2003   TGeoNode *node = gGeoManager->GetMother(off);
2004   if (!node) return 0;
2005   copyNo = node->GetNumber();
2006   return node->GetVolume()->GetNumber();
2007 }
2008
2009 //______________________________________________________________________________ 
2010 const char* TFluka::CurrentVolName() const
2011 {
2012 //
2013 // Return the current volume name
2014 //
2015   if (gGeoManager->IsOutside()) return 0;
2016   return gGeoManager->GetCurrentVolume()->GetName();
2017 }
2018
2019 //______________________________________________________________________________ 
2020 const char* TFluka::CurrentVolOffName(Int_t off) const
2021 {
2022 //
2023 // Return the volume name of the off'th mother of the current volume
2024 //
2025   if (off<0 || off>gGeoManager->GetLevel()) return 0;
2026   if (off==0) return CurrentVolName();
2027   TGeoNode *node = gGeoManager->GetMother(off);
2028   if (!node) return 0;
2029   return node->GetVolume()->GetName();
2030 }
2031
2032 const char* TFluka::CurrentVolPath() {
2033   // Return the current volume path
2034   return gGeoManager->GetPath(); 
2035 }
2036 //______________________________________________________________________________ 
2037 Int_t TFluka::CurrentMaterial(Float_t & a, Float_t & z, 
2038                       Float_t & dens, Float_t & radl, Float_t & absl) const
2039 {
2040 //
2041 //  Return the current medium number and material properties
2042 //
2043   Int_t copy;
2044   Int_t id  =  TFluka::CurrentVolID(copy);
2045   Int_t med =  TFluka::VolId2Mate(id);
2046   TGeoVolume*     vol = gGeoManager->GetCurrentVolume();
2047   TGeoMaterial*   mat = vol->GetMaterial();
2048   a    = mat->GetA();
2049   z    = mat->GetZ();
2050   dens = mat->GetDensity();
2051   radl = mat->GetRadLen();
2052   absl = mat->GetIntLen();
2053   
2054   return med;
2055 }
2056
2057 //______________________________________________________________________________ 
2058 void TFluka::Gmtod(Float_t* xm, Float_t* xd, Int_t iflag)
2059 {
2060 // Transforms a position from the world reference frame
2061 // to the current volume reference frame.
2062 //
2063 //  Geant3 desription:
2064 //  ==================
2065 //       Computes coordinates XD (in DRS) 
2066 //       from known coordinates XM in MRS 
2067 //       The local reference system can be initialized by
2068 //         - the tracking routines and GMTOD used in GUSTEP
2069 //         - a call to GMEDIA(XM,NUMED)
2070 //         - a call to GLVOLU(NLEVEL,NAMES,NUMBER,IER) 
2071 //             (inverse routine is GDTOM) 
2072 //
2073 //        If IFLAG=1  convert coordinates 
2074 //           IFLAG=2  convert direction cosinus
2075 //
2076 // ---
2077    Double_t xmL[3], xdL[3];
2078    Int_t i;
2079    for (i=0;i<3;i++) xmL[i]=xm[i];
2080    if (iflag == 1) gGeoManager->MasterToLocal(xmL,xdL);
2081    else            gGeoManager->MasterToLocalVect(xmL,xdL);
2082    for (i=0;i<3;i++) xd[i] = xdL[i];
2083 }
2084   
2085 //______________________________________________________________________________ 
2086 void TFluka::Gmtod(Double_t* xm, Double_t* xd, Int_t iflag)
2087 {
2088 //
2089 // See Gmtod(Float_t*, Float_t*, Int_t)
2090 //
2091    if (iflag == 1) gGeoManager->MasterToLocal(xm,xd);
2092    else            gGeoManager->MasterToLocalVect(xm,xd);
2093 }
2094
2095 //______________________________________________________________________________ 
2096 void TFluka::Gdtom(Float_t* xd, Float_t* xm, Int_t iflag)
2097 {
2098 // Transforms a position from the current volume reference frame
2099 // to the world reference frame.
2100 //
2101 //  Geant3 desription:
2102 //  ==================
2103 //  Computes coordinates XM (Master Reference System
2104 //  knowing the coordinates XD (Detector Ref System)
2105 //  The local reference system can be initialized by
2106 //    - the tracking routines and GDTOM used in GUSTEP
2107 //    - a call to GSCMED(NLEVEL,NAMES,NUMBER)
2108 //        (inverse routine is GMTOD)
2109 // 
2110 //   If IFLAG=1  convert coordinates
2111 //      IFLAG=2  convert direction cosinus
2112 //
2113 // ---
2114    Double_t xmL[3], xdL[3];
2115    Int_t i;
2116    for (i=0;i<3;i++) xdL[i] = xd[i];
2117    if (iflag == 1) gGeoManager->LocalToMaster(xdL,xmL);
2118    else            gGeoManager->LocalToMasterVect(xdL,xmL);
2119    for (i=0;i<3;i++) xm[i]=xmL[i];
2120 }
2121
2122 //______________________________________________________________________________ 
2123 void TFluka::Gdtom(Double_t* xd, Double_t* xm, Int_t iflag)
2124 {
2125 //
2126 // See Gdtom(Float_t*, Float_t*, Int_t)
2127 //
2128    if (iflag == 1) gGeoManager->LocalToMaster(xd,xm);
2129    else            gGeoManager->LocalToMasterVect(xd,xm);
2130 }
2131
2132 //______________________________________________________________________________
2133 TObjArray *TFluka::GetFlukaMaterials()
2134 {
2135 //
2136 // Get array of Fluka materials
2137    return fGeom->GetMatList();
2138 }   
2139
2140 //______________________________________________________________________________
2141 void TFluka::SetMreg(Int_t l, Int_t lttc) 
2142 {
2143 // Set current fluka region
2144    fCurrentFlukaRegion = l;
2145    fGeom->SetMreg(l,lttc);
2146 }
2147
2148
2149
2150
2151 //______________________________________________________________________________
2152 TString TFluka::ParticleName(Int_t pdg) const
2153 {
2154     // Return particle name for particle with pdg code pdg.
2155     Int_t ifluka = IdFromPDG(pdg);
2156     return TString((CHPPRP.btype[ifluka - kFLUKAcodemin]), 8);
2157 }
2158  
2159
2160 //______________________________________________________________________________
2161 Double_t TFluka::ParticleMass(Int_t pdg) const
2162 {
2163     // Return particle mass for particle with pdg code pdg.
2164     Int_t ifluka = IdFromPDG(pdg);
2165     return (PAPROP.am[ifluka - kFLUKAcodemin]);
2166 }
2167
2168 //______________________________________________________________________________
2169 Double_t TFluka::ParticleMassFPC(Int_t fpc) const
2170 {
2171     // Return particle mass for particle with Fluka particle code fpc
2172     return (PAPROP.am[fpc - kFLUKAcodemin]);
2173 }
2174
2175 //______________________________________________________________________________
2176 Double_t TFluka::ParticleCharge(Int_t pdg) const
2177 {
2178     // Return particle charge for particle with pdg code pdg.
2179     Int_t ifluka = IdFromPDG(pdg);
2180     return Double_t(PAPROP.ichrge[ifluka - kFLUKAcodemin]);
2181 }
2182
2183 //______________________________________________________________________________
2184 Double_t TFluka::ParticleLifeTime(Int_t pdg) const
2185 {
2186     // Return particle lifetime for particle with pdg code pdg.
2187     Int_t ifluka = IdFromPDG(pdg);
2188     return (PAPROP.tmnlf[ifluka - kFLUKAcodemin]);
2189 }
2190
2191 //______________________________________________________________________________
2192 void TFluka::Gfpart(Int_t pdg, char* name, Int_t& type, Float_t& mass, Float_t& charge, Float_t& tlife)
2193 {
2194     // Retrieve particle properties for particle with pdg code pdg.
2195     
2196     strcpy(name, ParticleName(pdg).Data());
2197     type   = ParticleMCType(pdg);
2198     mass   = ParticleMass(pdg);
2199     charge = ParticleCharge(pdg);
2200     tlife  = ParticleLifeTime(pdg);
2201 }
2202
2203 //______________________________________________________________________________
2204 void TFluka::PrintHeader()
2205 {
2206     //
2207     // Print a header
2208     printf("\n");
2209     printf("\n");    
2210     printf("------------------------------------------------------------------------------\n");
2211     printf("- You are using the TFluka Virtual Monte Carlo Interface to FLUKA.           -\n");    
2212     printf("- Please see the file fluka.out for FLUKA output and licensing information.  -\n");    
2213     printf("------------------------------------------------------------------------------\n");
2214     printf("\n");
2215     printf("\n");    
2216 }
2217
2218
2219 #define pshckp pshckp_
2220 #define ustckv ustckv_
2221
2222
2223 extern "C" {
2224   void pshckp(Double_t & px, Double_t & py, Double_t & pz, Double_t & e,
2225               Double_t & vx, Double_t & vy, Double_t & vz, Double_t & tof,
2226               Double_t & polx, Double_t & poly, Double_t & polz, Double_t & wgt, Int_t& ntr)
2227   {
2228     //
2229     // Pushes one cerenkov photon to the stack
2230     //
2231     
2232     TFluka* fluka =  (TFluka*) gMC;
2233     TVirtualMCStack* cppstack = fluka->GetStack();
2234     Int_t parent =  TRACKR.ispusr[mkbmx2-1];
2235     cppstack->PushTrack(0, parent, 50000050,
2236                         px, py, pz, e,
2237                         vx, vy, vz, tof,
2238                         polx, poly, polz,
2239                         kPCerenkov, ntr, wgt, 0);
2240     if (fluka->GetVerbosityLevel() >= 3)
2241             printf("pshckp: track=%d parent=%d lattc=%d %s\n", ntr, parent, TRACKR.lt1trk, fluka->CurrentVolName());
2242   }
2243     
2244     void ustckv(Int_t & nphot, Int_t & mreg, Double_t & x, Double_t & y, Double_t & z)
2245     {
2246         //
2247         // Calls stepping in order to signal cerenkov production
2248         //
2249         TFluka *fluka = (TFluka*)gMC;
2250         fluka->SetMreg(mreg, TRACKR.lt1trk); //LTCLCM.mlatm1);
2251         fluka->SetXsco(x);
2252         fluka->SetYsco(y);
2253         fluka->SetZsco(z);
2254         fluka->SetNCerenkov(nphot);
2255         fluka->SetCaller(kUSTCKV);
2256         if (fluka->GetVerbosityLevel() >= 3)
2257             printf("ustckv: %10d mreg=%d lattc=%d  newlat=%d (%f, %f, %f) edep=%f vol=%s\n",
2258                     nphot, mreg, TRACKR.lt1trk, LTCLCM.newlat, x, y, z, fluka->Edep(), fluka->CurrentVolName());
2259    
2260     // check region lattice consistency (debug Ernesto)
2261     // *****************************************************
2262    Int_t nodeId;
2263    Int_t volId = fluka->CurrentVolID(nodeId);
2264    Int_t crtlttc = gGeoManager->GetCurrentNodeId()+1;
2265
2266    if( mreg != volId  && !gGeoManager->IsOutside() ) {
2267        cout << "  ustckv:   track=" << TRACKR.ispusr[mkbmx2-1] << " pdg=" << fluka->PDGFromId(TRACKR.jtrack)
2268             << " icode=" << fluka->GetIcode() << " gNstep=" << fluka->GetNstep() << endl
2269             << "               fluka   mreg=" << mreg << " mlttc=" << TRACKR.lt1trk << endl
2270             << "               TGeo   volId=" << volId << " crtlttc=" << crtlttc << endl
2271             << "     common TRACKR   lt1trk=" << TRACKR.lt1trk << " lt2trk=" << TRACKR.lt2trk << endl
2272             << "     common LTCLCM   newlat=" << LTCLCM.newlat << " mlatld=" <<  LTCLCM.mlatld << endl
2273             << "                     mlatm1=" << LTCLCM.mlatm1 << " mltsen=" <<  LTCLCM.mltsen << endl
2274             << "                     mltsm1=" << LTCLCM.mltsm1 << " mlattc=" << LTCLCM.mlattc << endl;
2275         if( TRACKR.lt1trk == crtlttc ) cout << "   *************************************************************" << endl;
2276     }
2277     // *****************************************************
2278
2279
2280
2281         (TVirtualMCApplication::Instance())->Stepping();
2282     }
2283 }
2284
2285 //______________________________________________________________________________
2286 void TFluka::AddParticlesToPdgDataBase() const
2287 {
2288
2289 //
2290 // Add particles to the PDG data base
2291
2292     TDatabasePDG *pdgDB = TDatabasePDG::Instance();
2293
2294     const Int_t kion=10000000;
2295
2296     const Double_t kAu2Gev   = 0.9314943228;
2297     const Double_t khSlash   = 1.0545726663e-27;
2298     const Double_t kErg2Gev  = 1/1.6021773349e-3;
2299     const Double_t khShGev   = khSlash*kErg2Gev;
2300     const Double_t kYear2Sec = 3600*24*365.25;
2301 //
2302 // Ions
2303 //
2304
2305   pdgDB->AddParticle("Deuteron","Deuteron",2*kAu2Gev+8.071e-3,kTRUE,
2306                      0,3,"Ion",kion+10020);
2307   pdgDB->AddParticle("Triton","Triton",3*kAu2Gev+14.931e-3,kFALSE,
2308                      khShGev/(12.33*kYear2Sec),3,"Ion",kion+10030);
2309   pdgDB->AddParticle("Alpha","Alpha",4*kAu2Gev+2.424e-3,kTRUE,
2310                      khShGev/(12.33*kYear2Sec),6,"Ion",kion+20040);
2311   pdgDB->AddParticle("HE3","HE3",3*kAu2Gev+14.931e-3,kFALSE,
2312                      0,6,"Ion",kion+20030);
2313 }
2314
2315 //
2316 // Info about primary ionization electrons
2317 //
2318
2319 //______________________________________________________________________________
2320 Int_t TFluka::GetNPrimaryElectrons()
2321 {
2322     // Get number of primary electrons
2323     return ALLDLT.nalldl;
2324 }
2325
2326 //______________________________________________________________________________
2327 Double_t TFluka::GetPrimaryElectronKineticEnergy(Int_t i) const
2328 {
2329     // Returns kinetic energy of primary electron i
2330
2331     Double_t ekin = -1.;
2332     if (i >= 0 && i < ALLDLT.nalldl) {
2333         ekin =  ALLDLT.talldl[i];
2334     } else {
2335         Warning("GetPrimaryElectronKineticEnergy",
2336                 "Primary electron index out of range %d %d \n",
2337                 i, ALLDLT.nalldl);
2338     }
2339     return ekin;
2340 }
2341
2342 void TFluka::GetPrimaryElectronPosition(Int_t i, Double_t& x, Double_t& y, Double_t& z) const
2343 {
2344     // Returns position  of primary electron i
2345         if (i >= 0 && i < ALLDLT.nalldl) {
2346             x = ALLDLT.xalldl[i];
2347             y = ALLDLT.yalldl[i];
2348             z = ALLDLT.zalldl[i];
2349             return;
2350         } else {
2351             Warning("GetPrimaryElectronPosition",
2352                     "Primary electron index out of range %d %d \n",
2353                     i, ALLDLT.nalldl);
2354             return;
2355         }
2356         return;
2357 }
2358
2359