Zeroed fGenerators in the ctor.
[u/mrichter/AliRoot.git] / STEER / AliRun.cxx
1 ///////////////////////////////////////////////////////////////////////////////
2 //                                                                           //
3 //  Control class for Alice C++                                              //
4 //  Only one single instance of this class exists.                           //
5 //  The object is created in main program aliroot                            //
6 //  and is pointed by the global gAlice.                                     //
7 //                                                                           //
8 //   -Supports the list of all Alice Detectors (fModules).                 //
9 //   -Supports the list of particles (fParticles).                           //
10 //   -Supports the Trees.                                                    //
11 //   -Supports the geometry.                                                 //
12 //   -Supports the event display.                                            //
13 //Begin_Html
14 /*
15 <img src="gif/AliRunClass.gif">
16 */
17 //End_Html
18 //Begin_Html
19 /*
20 <img src="gif/alirun.gif">
21 */
22 //End_Html
23 //                                                                           //
24 ///////////////////////////////////////////////////////////////////////////////
25
26 #include <TFile.h>
27 #include <TRandom.h>
28 #include <TBRIK.h> 
29 #include <TNode.h> 
30 #include <AliMC.h> 
31 #include <TCint.h> 
32 #include <TSystem.h>
33
34 #include "GParticle.h"
35 #include "AliRun.h"
36 #include "AliModule.h"
37 #include "AliDisplay.h"
38
39 #include "AliCallf77.h" 
40  
41 #include <stdlib.h>
42 #include <stdio.h>
43 #include <string.h>
44  
45 AliRun *gAlice;
46
47 static AliHeader *header;
48
49 #ifndef WIN32
50
51 # define rxgtrak rxgtrak_
52 # define rxstrak rxstrak_
53 # define rxkeep  rxkeep_ 
54 # define rxouth  rxouth_
55 # define sxpart  sxpart_
56 #else
57
58 # define rxgtrak RXGTRAK 
59 # define rxstrak RXSTRAK 
60 # define rxkeep  RXKEEP  
61 # define rxouth  RXOUTH
62 # define sxpart  SXPART
63 #endif
64
65 static TArrayF sEventEnergy;
66 static TArrayF sSummEnergy;
67 static TArrayF sSum2Energy;
68
69 extern "C" void type_of_call sxpart();
70
71 ClassImp(AliRun)
72
73 //_____________________________________________________________________________
74 AliRun::AliRun()
75 {
76   //
77   // Default constructor for AliRun
78   //
79   header=&fHeader;
80   fRun       = 0;
81   fEvent     = 0;
82   fCurrent   = -1;
83   fModules = 0;
84   fGenerator = 0;
85   fTreeD     = 0;
86   fTreeK     = 0;
87   fTreeH     = 0;
88   fTreeE     = 0;
89   fTreeR     = 0;
90   fParticles = 0;
91   fGeometry  = 0;
92   fDisplay   = 0;
93   fField     = 0;
94   fMC        = 0;
95   fNdets     = 0;
96   fImedia    = 0;
97   fTrRmax    = 1.e10;
98   fTrZmax    = 1.e10;
99   fIdtmed    = 0;
100   fInitDone  = kFALSE;
101   fLego      = 0;
102 }
103
104 //_____________________________________________________________________________
105 AliRun::AliRun(const char *name, const char *title)
106   : TNamed(name,title)
107 {
108   //
109   //  Constructor for the main processor.
110   //  Creates the geometry
111   //  Creates the list of Detectors.
112   //  Creates the list of particles.
113   //
114   Int_t i;
115   
116   gAlice     = this;
117   fTreeD     = 0;
118   fTreeK     = 0;
119   fTreeH     = 0;
120   fTreeE     = 0;
121   fTreeR     = 0;
122   fTrRmax    = 1.e10;
123   fTrZmax    = 1.e10;
124   fGenerator = 0;
125   fInitDone  = kFALSE;
126   fLego      = 0;
127   fField     = 0;
128   
129   gROOT->GetListOfBrowsables()->Add(this,name);
130   //
131   // create the support list for the various Detectors
132   fModules = new TObjArray(77);
133   //
134   // Create the TNode geometry for the event display
135   
136   BuildSimpleGeometry();
137   
138
139   fNtrack=0;
140   fHgwmk=0;
141   fCurrent=-1;
142   header=&fHeader;
143   fRun       = 0;
144   fEvent     = 0;
145   //
146   // Create the particle stack
147   fParticles = new TClonesArray("GParticle",100);
148   
149   fDisplay = 0;
150   //
151   // Create default mag field
152   SetField();
153   //
154   fMC      = AliMC::GetMC();
155   //
156   //---------------Load detector names
157   
158   fNdets=21;
159   strcpy(fDnames[0],"BODY");
160   strcpy(fDnames[1],"NULL");
161   strcpy(fDnames[2],"ITS");
162   strcpy(fDnames[3],"MAG");
163   strcpy(fDnames[4],"TPC");
164   strcpy(fDnames[5],"TOF");
165   strcpy(fDnames[6],"PMD");
166   strcpy(fDnames[7],"PHOS");
167   strcpy(fDnames[8],"ZDC");
168   strcpy(fDnames[9],"FMD");
169   strcpy(fDnames[10],"RICH");
170   strcpy(fDnames[11],"MUON");
171   strcpy(fDnames[12],"FRAME");
172   strcpy(fDnames[13],"TRD");
173   strcpy(fDnames[14],"NULL");
174   strcpy(fDnames[15],"CASTOR");
175   strcpy(fDnames[16],"ABSO");
176   strcpy(fDnames[17],"SHIL");
177   strcpy(fDnames[18],"DIPO");
178   strcpy(fDnames[19],"HALL");
179   strcpy(fDnames[20],"PIPE");
180   
181   //
182   // Prepare the tracking medium lists
183   fImedia = new TArrayI(1000);
184   for(i=0;i<1000;i++) (*fImedia)[i]=-99;
185   fIdtmed = new Int_t[fNdets*100];
186   for(i=0;i<fNdets*100;i++) fIdtmed[i]=0;
187 }
188
189 //_____________________________________________________________________________
190 AliRun::~AliRun()
191 {
192   //
193   // Defaullt AliRun destructor
194   //
195   delete [] fIdtmed;
196   delete fImedia;
197   delete fField;
198   delete fMC;
199   delete fGeometry;
200   delete fDisplay;
201   delete fGenerator;
202   delete fLego;
203   delete fTreeD;
204   delete fTreeK;
205   delete fTreeH;
206   delete fTreeE;
207   delete fTreeR;
208   if (fModules) {
209     fModules->Delete();
210     delete fModules;
211   }
212   if (fParticles) {
213     fParticles->Delete();
214     delete fParticles;
215   }
216 }
217
218 //_____________________________________________________________________________
219 void AliRun::AddHit(Int_t id, Int_t track, Int_t *vol, Float_t *hits) const
220 {
221   //
222   //  Add a hit to detector id
223   //
224   TObjArray &dets = *fModules;
225   if(dets[id]) ((AliModule*) dets[id])->AddHit(track,vol,hits);
226 }
227
228 //_____________________________________________________________________________
229 void AliRun::AddDigit(Int_t id, Int_t *tracks, Int_t *digits) const
230 {
231   //
232   // Add digit to detector id
233   //
234   TObjArray &dets = *fModules;
235   if(dets[id]) ((AliModule*) dets[id])->AddDigit(tracks,digits);
236 }
237
238 //_____________________________________________________________________________
239 void AliRun::Browse(TBrowser *b)
240 {
241   //
242   // Called when the item "Run" is clicked on the left pane
243   // of the Root browser.
244   // It displays the Root Trees and all detectors.
245   //
246   if (fTreeK) b->Add(fTreeK,fTreeK->GetName());
247   if (fTreeH) b->Add(fTreeH,fTreeH->GetName());
248   if (fTreeD) b->Add(fTreeD,fTreeD->GetName());
249   if (fTreeE) b->Add(fTreeE,fTreeE->GetName());
250   if (fTreeR) b->Add(fTreeR,fTreeR->GetName());
251   
252   TIter next(fModules);
253   AliModule *detector;
254   while((detector = (AliModule*)next())) {
255     b->Add(detector,detector->GetName());
256   }
257 }
258
259 //_____________________________________________________________________________
260 void AliRun::Build()
261 {
262   //
263   // Initialize Alice geometry
264   // Dummy routine
265   //
266 }
267  
268 //_____________________________________________________________________________
269 void AliRun::BuildSimpleGeometry()
270 {
271   //
272   // Create a simple TNode geometry used by Root display engine
273   //
274   // Initialise geometry
275   //
276   fGeometry = new TGeometry("AliceGeom","Galice Geometry for Hits");
277   new TMaterial("void","Vacuum",0,0,0);  //Everything is void
278   TBRIK *brik = new TBRIK("S_alice","alice volume","void",2000,2000,3000);
279   brik->SetVisibility(0);
280   new TNode("alice","alice","S_alice");
281 }
282
283 //_____________________________________________________________________________
284 void AliRun::CleanDetectors()
285 {
286   //
287   // Clean Detectors at the end of event
288   //
289   TIter next(fModules);
290   AliModule *detector;
291   while((detector = (AliModule*)next())) {
292     detector->FinishEvent();
293   }
294 }
295
296 //_____________________________________________________________________________
297 void AliRun::CleanParents()
298 {
299   //
300   // Clean Particles stack.
301   // Set parent/child relations
302   //
303   TClonesArray &particles = *(gAlice->Particles());
304   GParticle *part;
305   int i;
306   for(i=0; i<fNtrack; i++) {
307     part = (GParticle *)particles.UncheckedAt(i);
308     if(!part->TestBit(Children_Bit)) {
309       part->SetFirstChild(-1);
310       part->SetLastChild(-1);
311     }
312   }
313 }
314
315 //_____________________________________________________________________________
316 Int_t AliRun::DistancetoPrimitive(Int_t, Int_t)
317 {
318   //
319   // Return the distance from the mouse to the AliRun object
320   // Dummy routine
321   //
322   return 9999;
323 }
324
325 //_____________________________________________________________________________
326 void AliRun::DumpPart (Int_t i)
327 {
328   //
329   // Dumps particle i in the stack
330   //
331   TClonesArray &particles = *fParticles;
332   ((GParticle*) particles[i])->Dump();
333 }
334
335 //_____________________________________________________________________________
336 void AliRun::DumpPStack ()
337 {
338   //
339   // Dumps the particle stack
340   //
341   TClonesArray &particles = *fParticles;
342   printf(
343          "\n\n=======================================================================\n");
344   for (Int_t i=0;i<fNtrack;i++) 
345     {
346       printf("-> %d ",i); ((GParticle*) particles[i])->Dump();
347       printf("--------------------------------------------------------------\n");
348     }
349   printf(
350          "\n=======================================================================\n\n");
351 }
352
353 //_____________________________________________________________________________
354 void AliRun::SetField(Int_t type, Int_t version, Float_t scale,
355                       Float_t maxField, char* filename)
356 {
357   //
358   //  Set magnetic field parameters
359   //  type      Magnetic field transport flag 0=no field, 2=helix, 3=Runge Kutta
360   //  version   Magnetic field map version (only 1 active now)
361   //  scale     Scale factor for the magnetic field
362   //  maxField  Maximum value for the magnetic field
363
364   //
365   // --- Sanity check on mag field flags
366   if(type<0 || type > 2) {
367     printf(" Invalid magnetic field flag: %5d; Helix tracking chosen instead\n"
368            ,type);
369     type=2;
370   }
371   if(fField) delete fField;
372   if(version==1) {
373     fField = new AliMagFC("Map1"," ",type,version,scale,maxField);
374   } else if(version<=3) {
375     fField = new AliMagFCM("Map2-3",filename,type,version,scale,maxField);
376     fField->ReadField();
377   } else {
378     printf("Invalid map %d\n",version);
379   }
380 }
381
382 //_____________________________________________________________________________
383 void AliRun::FillTree()
384 {
385   //
386   // Fills all AliRun TTrees
387   //
388   if (fTreeK) fTreeK->Fill();
389   if (fTreeH) fTreeH->Fill();
390   if (fTreeD) fTreeD->Fill();
391   if (fTreeR) fTreeR->Fill();
392 }
393  
394 //_____________________________________________________________________________
395 void AliRun::FinishPrimary()
396 {
397   //
398   // Called  at the end of each primary track
399   //
400   
401   // This primary is finished, purify stack
402   gAlice->PurifyKine();
403
404   // Write out hits if any
405   if (gAlice->TreeH()) {
406     gAlice->TreeH()->Fill();
407   }
408   
409   // Reset Hits info
410   gAlice->ResetHits();
411 }
412
413 //_____________________________________________________________________________
414 void AliRun::FinishEvent()
415 {
416   //
417   // Called at the end of the event.
418   //
419   
420   //Update the energy deposit tables
421   Int_t i;
422   for(i=0;i<sEventEnergy.GetSize();i++) {
423     sSummEnergy[i]+=sEventEnergy[i];
424     sSum2Energy[i]+=sEventEnergy[i]*sEventEnergy[i];
425   }
426   sEventEnergy.Reset();
427   
428   // Clean detector information
429   CleanDetectors();
430   
431   // Write out the kinematics
432   if (fTreeK) {
433     CleanParents();
434     fTreeK->Fill();
435   }
436   
437   // Write out the digits
438   if (fTreeD) {
439     fTreeD->Fill();
440     ResetDigits();
441   }
442   
443   // Write out reconstructed clusters  
444   if (fTreeR) {
445     fTreeR->Fill();
446   }
447
448   // Write out the event Header information
449   if (fTreeE) fTreeE->Fill();
450   
451   // Reset stack info
452   ResetStack();
453   
454   // Write Tree headers
455   Int_t ievent = fHeader.GetEvent();
456   char hname[30];
457   sprintf(hname,"TreeK%d",ievent);
458   if (fTreeK) fTreeK->Write(hname);
459   sprintf(hname,"TreeH%d",ievent);
460   if (fTreeH) fTreeH->Write(hname);
461   sprintf(hname,"TreeD%d",ievent);
462   if (fTreeD) fTreeD->Write(hname);
463   sprintf(hname,"TreeR%d",ievent);
464   if (fTreeR) fTreeR->Write(hname);
465 }
466
467 //_____________________________________________________________________________
468 void AliRun::FinishRun()
469 {
470   //
471   // Called at the end of the run.
472   //
473
474   // Clean detector information
475   TIter next(fModules);
476   AliModule *detector;
477   while((detector = (AliModule*)next())) {
478     detector->FinishRun();
479   }
480   
481   //Output energy summary tables
482   EnergySummary();
483   
484   // file is retrieved from whatever tree
485   TFile *File = 0;
486   if (fTreeK) File = fTreeK->GetCurrentFile();
487   if ((!File) && (fTreeH)) File = fTreeH->GetCurrentFile();
488   if ((!File) && (fTreeD)) File = fTreeD->GetCurrentFile();
489   if ((!File) && (fTreeE)) File = fTreeE->GetCurrentFile();
490   if( NULL==File ) {
491     Error("FinishRun","There isn't root file!");
492     exit(1);
493   }
494   File->cd();
495   fTreeE->Write();
496   
497   // Clean tree information
498   delete fTreeK; fTreeK = 0;
499   delete fTreeH; fTreeH = 0;
500   delete fTreeD; fTreeD = 0;
501   delete fTreeR; fTreeR = 0;
502   delete fTreeE; fTreeE = 0;
503   
504   // Write AliRun info and all detectors parameters
505   Write();
506   
507   // Close output file
508   File->Write();
509   File->Close();
510 }
511
512 //_____________________________________________________________________________
513 void AliRun::FlagTrack(Int_t track)
514 {
515   //
516   // Flags a track and all its family tree to be kept
517   //
518   int curr;
519   GParticle *particle;
520
521   curr=track;
522   while(1) {
523     particle=(GParticle*)fParticles->UncheckedAt(curr);
524     
525     // If the particle is flagged the three from here upward is saved already
526     if(particle->TestBit(Keep_Bit)) return;
527     
528     // Save this particle
529     particle->SetBit(Keep_Bit);
530     
531     // Move to father if any
532     if((curr=particle->GetParent())==-1) return;
533   }
534 }
535  
536 //_____________________________________________________________________________
537 void AliRun::EnergySummary()
538 {
539   //
540   // Print summary of deposited energy
541   //
542
543   AliMC* pMC = AliMC::GetMC();
544
545   Int_t ndep=0;
546   Float_t edtot=0;
547   Float_t ed, ed2;
548   Int_t kn, i, left, j, id;
549   const Float_t zero=0;
550   Int_t ievent=fHeader.GetEvent()+1;
551   //
552   // Energy loss information
553   if(ievent) {
554     printf("***************** Energy Loss Information per event (GEV) *****************\n");
555     for(kn=1;kn<sEventEnergy.GetSize();kn++) {
556       ed=sSummEnergy[kn];
557       if(ed>0) {
558         sEventEnergy[ndep]=kn;
559         if(ievent>1) {
560           ed=ed/ievent;
561           ed2=sSum2Energy[kn];
562           ed2=ed2/ievent;
563           ed2=100*TMath::Sqrt(TMath::Max(ed2-ed*ed,zero))/ed;
564         } else 
565           ed2=99;
566         sSummEnergy[ndep]=ed;
567         sSum2Energy[ndep]=TMath::Min((Float_t) 99.,TMath::Max(ed2,zero));
568         edtot+=ed;
569         ndep++;
570       }
571     }
572     for(kn=0;kn<(ndep-1)/3+1;kn++) {
573       left=ndep-kn*3;
574       for(i=0;i<(3<left?3:left);i++) {
575         j=kn*3+i;
576         id=Int_t (sEventEnergy[j]+0.1);
577         printf(" %s %10.3f +- %10.3f%%;",pMC->VolName(id),sSummEnergy[j],sSum2Energy[j]);
578       }
579       printf("\n");
580     }
581     //
582     // Relative energy loss in different detectors
583     printf("******************** Relative Energy Loss per event ********************\n");
584     printf("Total energy loss per event %10.3f GeV\n",edtot);
585     for(kn=0;kn<(ndep-1)/5+1;kn++) {
586       left=ndep-kn*5;
587       for(i=0;i<(5<left?5:left);i++) {
588         j=kn*5+i;
589         id=Int_t (sEventEnergy[j]+0.1);
590         printf(" %s %10.3f%%;",pMC->VolName(id),100*sSummEnergy[j]/edtot);
591       }
592       printf("\n");
593     }
594     for(kn=0;kn<75;kn++) printf("*"); 
595     printf("\n");
596   }
597   //
598   // Reset the TArray's
599   sEventEnergy.Set(0);
600   sSummEnergy.Set(0);
601   sSum2Energy.Set(0);
602 }
603
604 //_____________________________________________________________________________
605 AliModule *AliRun::GetModule(const char *name)
606 {
607   //
608   // Return pointer to detector from name
609   //
610   return (AliModule*)fModules->FindObject(name);
611 }
612  
613 //_____________________________________________________________________________
614 Int_t AliRun::GetModuleID(const char *name)
615 {
616   //
617   // Return galice internal detector identifier from name
618   //
619   Int_t i;
620   for(i=0;i<fNdets;i++) if(!strcmp(fDnames[i],name)) {
621     return i;
622   }
623   printf(" * GetDetectorID * Detector %s not found: returning -1\n",name);
624   return -1;
625 }
626  
627 //_____________________________________________________________________________
628 Int_t AliRun::GetEvent(Int_t event)
629 {
630   //
631   // Connect the Trees Kinematics and Hits for event # event
632   // Set branch addresses
633   //
634   fHeader.SetEvent(event);
635
636   // Reset existing structures
637   ResetStack();
638   ResetHits();
639   ResetDigits();
640   
641   // Delete Trees already connected
642   if (fTreeK) delete fTreeK;
643   if (fTreeH) delete fTreeH;
644   if (fTreeD) delete fTreeD;
645   if (fTreeR) delete fTreeR;
646   
647   // Get Kine Tree from file
648   char treeName[20];
649   sprintf(treeName,"TreeK%d",event);
650   fTreeK = (TTree*)gDirectory->Get(treeName);
651   if (fTreeK) fTreeK->SetBranchAddress("Particles", &fParticles);
652   else        printf("ERROR: cannot find Kine Tree for event:%d\n",event);
653   
654   // Get Hits Tree header from file
655   sprintf(treeName,"TreeH%d",event);
656   fTreeH = (TTree*)gDirectory->Get(treeName);
657   if (!fTreeH) {
658     printf("ERROR: cannot find Hits Tree for event:%d\n",event);
659     return 0;
660   }
661   
662   // Get Digits Tree header from file
663   sprintf(treeName,"TreeD%d",event);
664   fTreeD = (TTree*)gDirectory->Get(treeName);
665   if (!fTreeD) {
666     printf("WARNING: cannot find Digits Tree for event:%d\n",event);
667   }
668   
669   
670   // Get Reconstruct Tree header from file
671   sprintf(treeName,"TreeR%d",event);
672   fTreeR = (TTree*)gDirectory->Get(treeName);
673   if (!fTreeR) {
674     //    printf("WARNING: cannot find Reconstructed Tree for event:%d\n",event);
675   }
676  
677   // Set Trees branch addresses
678   TIter next(fModules);
679   AliModule *detector;
680   while((detector = (AliModule*)next())) {
681     detector->SetTreeAddress();
682   }
683   
684   if (fTreeK) fTreeK->GetEvent(0);
685   fNtrack = Int_t (fParticles->GetEntries());
686   return fNtrack;
687 }
688
689 //_____________________________________________________________________________
690 TGeometry *AliRun::GetGeometry()
691 {
692   //
693   // Import Alice geometry from current file
694   // Return pointer to geometry object
695   //
696   if (!fGeometry) fGeometry = (TGeometry*)gDirectory->Get("AliceGeom");
697   //
698   // Unlink and relink nodes in detectors
699   // This is bad and there must be a better way...
700   //
701   TList *tnodes=fGeometry->GetListOfNodes(); 
702   TNode *alice=(TNode*)tnodes->At(0);
703   TList *gnodes=alice->GetListOfNodes();
704   
705   TIter next(fModules);
706   AliModule *detector;
707   while((detector = (AliModule*)next())) {
708     detector->SetTreeAddress();
709     TList *dnodes=detector->Nodes();
710     Int_t j;
711     TNode *node, *node1;
712     for ( j=0; j<dnodes->GetSize(); j++) {
713       node = (TNode*) dnodes->At(j);
714       node1 = (TNode*) gnodes->FindObject(node->GetName());
715       dnodes->Remove(node);
716       dnodes->AddAt(node1,j);
717     }
718   }
719   return fGeometry;
720 }
721
722 //_____________________________________________________________________________
723 void AliRun::GetNextTrack(Int_t &mtrack, Int_t &ipart, Float_t *pmom,
724                           Float_t &e, Float_t *vpos, Float_t *polar,
725                           Float_t &tof)
726 {
727   //
728   // Return next track from stack of particles
729   //
730   fCurrent=-1;
731   GParticle *track;
732   for(Int_t i=fNtrack-1; i>=0; i--) {
733     track=(GParticle*) fParticles->UncheckedAt(i);
734     if(!track->TestBit(Done_Bit)) {
735       //
736       // The track has not yet been processed
737       fCurrent=i;
738       ipart=track->GetKF();
739       pmom[0]=track->GetPx();
740       pmom[1]=track->GetPy(); 
741       pmom[2]=track->GetPz();
742       e     =track->GetEnergy();
743       vpos[0]=track->GetVx();
744       vpos[1]=track->GetVy();
745       vpos[2]=track->GetVz();
746       polar[0]=track->GetPolx();
747       polar[1]=track->GetPoly();
748       polar[2]=track->GetPolz();
749       tof=track->GetTime();
750       track->SetBit(Done_Bit);
751       break;
752     }
753   }
754   mtrack=fCurrent;
755   //
756   // stop and start timer when we start a primary track
757   Int_t nprimaries = fHeader.GetNprimary();
758   if (fCurrent >= nprimaries) return;
759   if (fCurrent < nprimaries-1) {
760     fTimer.Stop();
761     track=(GParticle*) fParticles->UncheckedAt(fCurrent+1);
762     track->SetProcessTime(fTimer.CpuTime());
763   }
764   fTimer.Start();
765 }
766
767 //_____________________________________________________________________________
768 Int_t AliRun::GetPrimary(Int_t track)
769 {
770   //
771   // return number of primary that has generated track
772   //
773   int current, parent;
774   GParticle *part;
775   //
776   parent=track;
777   while (1) {
778     current=parent;
779     part = (GParticle *)fParticles->UncheckedAt(current);
780     parent=part->GetParent();
781     if(parent<0) return current;
782   }
783 }
784  
785 //_____________________________________________________________________________
786 void AliRun::Init(const char *setup)
787 {
788   //
789   // Initialize the Alice setup
790   //
791
792   gROOT->LoadMacro(setup);
793   gInterpreter->ProcessLine("Config();");
794
795   AliMC* pMC = AliMC::GetMC();
796
797   pMC->Gpart();  //Create standard Geant particles
798   sxpart();        //Define additional particles
799
800   TObject *objfirst, *objlast;
801
802   //
803   //=================Create Materials, geometry, histograms, etc
804    TIter next(fModules);
805    AliModule *detector;
806    while((detector = (AliModule*)next())) {
807       detector->SetTreeAddress();
808       objlast = gDirectory->GetList()->Last();
809       
810       // Initialise detector materials, geometry, histograms,etc
811       detector->CreateMaterials();
812       detector->CreateGeometry();
813       detector->BuildGeometry();
814       detector->Init();
815       
816       // Add Detector histograms in Detector list of histograms
817       if (objlast) objfirst = gDirectory->GetList()->After(objlast);
818       else         objfirst = gDirectory->GetList()->First();
819       while (objfirst) {
820         detector->Histograms()->Add(objfirst);
821         objfirst = gDirectory->GetList()->After(objfirst);
822       }
823    }
824    SetTransPar(); //Read the cuts for all materials
825    
826    MediaTable(); //Build the special IMEDIA table
827    
828    //Close the geometry structure
829    pMC->Ggclos();
830    
831    //Initialise geometry deposition table
832    sEventEnergy.Set(pMC->NofVolumes()+1);
833    sSummEnergy.Set(pMC->NofVolumes()+1);
834    sSum2Energy.Set(pMC->NofVolumes()+1);
835    
836    //Create the color table
837    pMC->SetColors();
838    
839    //Compute cross-sections
840    pMC->Gphysi();
841    
842    //Write Geometry object to current file.
843    fGeometry->Write();
844    
845    fInitDone = kTRUE;
846 }
847
848 //_____________________________________________________________________________
849 void AliRun::MediaTable()
850 {
851   //
852   // Built media table to get from the media number to
853   // the detector id
854   //
855   Int_t kz, ibeg, nz, idt, lz, i, k, ind;
856   TObjArray &dets = *gAlice->Detectors();
857   AliModule *det;
858   //
859   // For all detectors
860   for (kz=0;kz<fNdets;kz++) {
861     // If detector is defined
862     if((det=(AliModule*) dets[kz])) {
863       ibeg=100*kz-1;
864       for(nz=ibeg==-1?1:0;nz<100;nz++) {
865         // Find max and min material number
866         if((idt=fIdtmed[ibeg+nz])) {
867           det->LoMedium() = det->LoMedium() < idt ? det->LoMedium() : idt;
868           det->HiMedium() = det->HiMedium() > idt ? det->HiMedium() : idt;
869         }
870       }
871       if(det->LoMedium() > det->HiMedium()) {
872         det->LoMedium() = 0;
873         det->HiMedium() = 0;
874       } else {
875         if(det->HiMedium() > fImedia->GetSize()) {
876           Error("MediaTable","Increase fImedia");
877           return;
878         }
879         // Tag all materials in rage as belonging to detector kz
880         for(lz=det->LoMedium(); lz<= det->HiMedium(); lz++) {
881           (*fImedia)[lz]=kz;
882         }
883       }
884     }
885   }
886   //
887   // Print summary table
888   printf(" Traking media ranges:\n");
889   for(i=0;i<(fNdets-1)/6+1;i++) {
890     for(k=0;k< (6<fNdets-i*6?6:fNdets-i*6);k++) {
891       ind=i*6+k;
892       det=(AliModule*)dets[ind];
893       if(det)
894         printf(" %6s: %3d -> %3d;",det->GetName(),det->LoMedium(),
895                det->HiMedium());
896       else
897         printf(" %6s: %3d -> %3d;","NULL",0,0);
898     }
899     printf("\n");
900   }
901 }
902
903 //____________________________________________________________________________
904 void AliRun::SetGenerator(AliGenerator *generator)
905 {
906   //
907   // Load the event generator
908   //
909   if(!fGenerator) fGenerator = generator;
910 }
911
912 //____________________________________________________________________________
913 void AliRun::SetTransPar(char* filename)
914 {
915   //
916   // Read filename to set the transport parameters
917   //
918
919   AliMC* pMC = AliMC::GetMC();
920
921   const Int_t ncuts=10;
922   const Int_t nflags=11;
923   const Int_t npars=ncuts+nflags;
924   const char pars[npars][7] = {"CUTGAM" ,"CUTELE","CUTNEU","CUTHAD","CUTMUO",
925                                "BCUTE","BCUTM","DCUTE","DCUTM","PPCUTM","ANNI",
926                                "BREM","COMP","DCAY","DRAY","HADR","LOSS",
927                                "MULS","PAIR","PHOT","RAYL"};
928   char line[256];
929   char* filtmp;
930   Float_t cut[ncuts];
931   Int_t flag[nflags];
932   Int_t i, itmed, iret, ktmed, kz;
933   FILE *lun;
934   //
935   // See whether the file is there
936   filtmp=gSystem->ExpandPathName(filename);
937   lun=fopen(filtmp,"r");
938   delete [] filtmp;
939   if(!lun) {
940     printf(" * AliRun::SetTransPar * file %s does not exist!\n",filename);
941     return;
942   }
943   //
944   printf(" "); for(i=0;i<60;i++) printf("*"); printf("\n");
945   printf(" *%59s\n","*");
946   printf(" *       Please check carefully what you are doing!%10s\n","*");
947   printf(" *%59s\n","*");
948   //
949   while(1) {
950     // Initialise cuts and flags
951     for(i=0;i<ncuts;i++) cut[i]=-99;
952     for(i=0;i<nflags;i++) flag[i]=-99;
953     itmed=0;
954     for(i=0;i<256;i++) line[i]='\0';
955     // Read up to the end of line excluded
956     iret=fscanf(lun,"%[^\n]",line);
957     if(iret<0) {
958       //End of file
959       fclose(lun);
960       printf(" *%59s\n","*");
961       printf(" "); for(i=0;i<60;i++) printf("*"); printf("\n");
962       return;
963     }
964     // Read the end of line
965     fscanf(lun,"%*c");
966     if(!iret) continue;
967     if(line[0]=='*') continue;
968     // Read the numbers
969     iret=sscanf(line,"%d %f %f %f %f %f %f %f %f %f %f %d %d %d %d %d %d %d %d %d %d %d",
970                 &itmed,&cut[0],&cut[1],&cut[2],&cut[3],&cut[4],&cut[5],&cut[6],&cut[7],&cut[8],&cut[9],
971                 &flag[0],&flag[1],&flag[2],&flag[3],&flag[4],&flag[5],&flag[6],&flag[7],&flag[8],
972                 &flag[9],&flag[10]);
973     if(!iret) continue;
974     if(iret<0) {
975       //reading error
976       printf(" *   Error reading file %s\n",filename);
977       continue;
978     }
979     // Check that the tracking medium code is valid
980     if(0<itmed && itmed < 100*fNdets) {
981       ktmed=fIdtmed[itmed-1];
982       if(!ktmed) {
983         printf(" *     Invalid tracking medium code %d *\n",itmed);
984         continue;
985       }
986       // Set energy thresholds
987       for(kz=0;kz<ncuts;kz++) {
988         if(cut[kz]>=0) {
989           printf(" *  %-6s set to %10.3E for tracking medium code %4d  *\n",pars[kz],cut[kz],itmed);
990           pMC->Gstpar(ktmed,pars[kz],cut[kz]);
991         }
992       }
993       // Set transport mechanisms
994       for(kz=0;kz<nflags;kz++) {
995         if(flag[kz]>=0) {
996           printf(" *  %-6s set to %10d for tracking medium code %4d  *\n",pars[ncuts+kz],flag[kz],itmed);
997           pMC->Gstpar(ktmed,pars[ncuts+kz],Float_t(flag[kz]));
998         }
999       }
1000     } else {
1001       printf(" *     Invalid tracking medium code %d *\n",itmed);
1002       continue;
1003     }
1004   }
1005 }
1006
1007 //_____________________________________________________________________________
1008 void AliRun::MakeTree(Option_t *option)
1009 {
1010   //
1011   //  Create the ROOT trees
1012   //  Loop on all detectors to create the Root branch (if any)
1013   //
1014
1015   //
1016   // Analyse options
1017   char *K = strstr(option,"K");
1018   char *H = strstr(option,"H");
1019   char *E = strstr(option,"E");
1020   char *D = strstr(option,"D");
1021   char *R = strstr(option,"R");
1022   //
1023   if (K && !fTreeK) fTreeK = new TTree("TK","Kinematics");
1024   if (H && !fTreeH) fTreeH = new TTree("TH","Hits");
1025   if (D && !fTreeD) fTreeD = new TTree("TD","Digits");
1026   if (E && !fTreeE) fTreeE = new TTree("TE","Header");
1027   if (R && !fTreeR) fTreeR = new TTree("TR","Reconstruction");
1028   if (fTreeH) fTreeH->SetAutoSave(1000000000); //no autosave
1029   //
1030   // Create a branch for hits/digits for each detector
1031   // Each branch is a TClonesArray. Each data member of the Hits classes
1032   // will be in turn a subbranch of the detector master branch
1033   TIter next(fModules);
1034   AliModule *detector;
1035   while((detector = (AliModule*)next())) {
1036      if (H || D || R) detector->MakeBranch(option);
1037   }
1038   //  Create a branch for particles
1039   if (fTreeK && K) fTreeK->Branch("Particles",&fParticles,4000);
1040   
1041   //  Create a branch for Header
1042   if (fTreeE && E) fTreeE->Branch("Header","AliHeader",&header,4000);
1043 }
1044
1045 //_____________________________________________________________________________
1046 Int_t AliRun::PurifyKine(Int_t lastSavedTrack, Int_t nofTracks)
1047 {
1048   //
1049   // PurifyKine with external parameters
1050   //
1051   fHgwmk = lastSavedTrack;
1052   fNtrack = nofTracks;
1053   PurifyKine();
1054   return fHgwmk;
1055 }
1056
1057 //_____________________________________________________________________________
1058 void AliRun::PurifyKine()
1059 {
1060   //
1061   // Compress kinematic tree keeping only flagged particles
1062   // and renaming the particle id's in all the hits
1063   //
1064   TClonesArray &particles = *fParticles;
1065   int nkeep=fHgwmk+1, parent, i;
1066   GParticle *part, *partnew, *father;
1067   AliHit *OneHit;
1068   int *map = new int[particles.GetEntries()];
1069
1070   // Save in Header total number of tracks before compression
1071   fHeader.SetNtrack(fHeader.GetNtrack()+fNtrack-fHgwmk);
1072
1073   // Preset map, to be removed later
1074   for(i=0; i<fNtrack; i++) {
1075     if(i<=fHgwmk) map[i]=i ; else map[i] = -99 ;}
1076   // Second pass, build map between old and new numbering
1077   for(i=fHgwmk+1; i<fNtrack; i++) {
1078     part = (GParticle *)particles.UncheckedAt(i);
1079     if(part->TestBit(Keep_Bit)) {
1080       
1081       // This particle has to be kept
1082       map[i]=nkeep;
1083       if(i!=nkeep) {
1084         
1085         // Old and new are different, have to copy
1086         partnew = (GParticle *)particles.UncheckedAt(nkeep);
1087         *partnew = *part;
1088       } else partnew = part;
1089       
1090       // as the parent is always *before*, it must be already
1091       // in place. This is what we are checking anyway!
1092       if((parent=partnew->GetParent())>fHgwmk) {
1093         if(map[parent]==-99) printf("map[%d] = -99!\n",parent);
1094         partnew->SetParent(map[parent]);
1095       }
1096       nkeep++;
1097     }
1098   }
1099   fNtrack=nkeep;
1100   
1101   // Fix children information
1102   for (i=fHgwmk+1; i<fNtrack; i++) {
1103     part = (GParticle *)particles.UncheckedAt(i);
1104     parent = part->GetParent();
1105     father = (GParticle *)particles.UncheckedAt(parent);
1106     if(father->TestBit(Children_Bit)) {
1107       
1108       if(i<father->GetFirstChild()) father->SetFirstChild(i);
1109       if(i>father->GetLastChild())  father->SetLastChild(i);
1110     } else {
1111       // Iitialise children info for first pass
1112       father->SetFirstChild(i);
1113       father->SetLastChild(i);
1114       father->SetBit(Children_Bit);
1115     }
1116   }
1117   
1118   // Now loop on all detectors and reset the hits
1119   TIter next(fModules);
1120   AliModule *detector;
1121   while((detector = (AliModule*)next())) {
1122     if (!detector->Hits()) continue;
1123     TClonesArray &vHits=*(detector->Hits());
1124     if(vHits.GetEntries() != detector->GetNhits())
1125       printf("vHits.GetEntries()!=detector->GetNhits(): %d != %d\n",
1126              vHits.GetEntries(),detector->GetNhits());
1127     for (i=0; i<detector->GetNhits(); i++) {
1128       OneHit = (AliHit *)vHits.UncheckedAt(i);
1129       OneHit->SetTrack(map[OneHit->GetTrack()]);
1130     }
1131   }
1132
1133   fHgwmk=nkeep-1;
1134   particles.SetLast(fHgwmk);
1135   delete [] map;
1136 }
1137
1138 //_____________________________________________________________________________
1139 void AliRun::Reset(Int_t run, Int_t idevent)
1140 {
1141   //
1142   //  Reset all Detectors & kinematics & trees
1143   //
1144   ResetStack();
1145   ResetHits();
1146   ResetDigits();
1147
1148   // Initialise event header
1149   fHeader.Reset(run,idevent);
1150
1151   if(fTreeK) fTreeK->Reset();
1152   if(fTreeH) fTreeH->Reset();
1153   if(fTreeD) fTreeD->Reset();
1154 }
1155
1156 //_____________________________________________________________________________
1157 void AliRun::ResetDigits()
1158 {
1159   //
1160   //  Reset all Detectors digits
1161   //
1162   TIter next(fModules);
1163   AliModule *detector;
1164   while((detector = (AliModule*)next())) {
1165      detector->ResetDigits();
1166   }
1167 }
1168
1169 //_____________________________________________________________________________
1170 void AliRun::ResetHits()
1171 {
1172   //
1173   //  Reset all Detectors hits
1174   //
1175   TIter next(fModules);
1176   AliModule *detector;
1177   while((detector = (AliModule*)next())) {
1178      detector->ResetHits();
1179   }
1180 }
1181
1182 //_____________________________________________________________________________
1183 void AliRun::ResetPoints()
1184 {
1185   //
1186   // Reset all Detectors points
1187   //
1188   TIter next(fModules);
1189   AliModule *detector;
1190   while((detector = (AliModule*)next())) {
1191      detector->ResetPoints();
1192   }
1193 }
1194
1195 //_____________________________________________________________________________
1196 void AliRun::Run(Int_t nevent, const char *setup)
1197 {
1198   //
1199   // Main function to be called to process a galice run
1200   // example
1201   //    Root > gAlice.Run(); 
1202   // a positive number of events will cause the finish routine
1203   // to be called
1204   //
1205
1206   Int_t i, todo;
1207   // check if initialisation has been done
1208   if (!fInitDone) Init(setup);
1209   
1210   AliMC* pMC = AliMC::GetMC();
1211
1212   // Create the Root Tree with one branch per detector
1213   if(!fEvent) {
1214     gAlice->MakeTree("KHDER");
1215   }
1216
1217   todo = TMath::Abs(nevent);
1218   for (i=0; i<todo; i++) {
1219   // Process one run (one run = one event)
1220      gAlice->Reset(fRun, fEvent);
1221      pMC->Gtrigi();
1222      pMC->Gtrigc();
1223      pMC->Gtrig();
1224      gAlice->FinishEvent();
1225      fEvent++;
1226   }
1227   
1228   // End of this run, close files
1229   if(nevent>0) gAlice->FinishRun();
1230 }
1231
1232 //_____________________________________________________________________________
1233 void AliRun::RunLego(const char *setup,Int_t ntheta,Float_t themin,
1234                      Float_t themax,Int_t nphi,Float_t phimin,Float_t phimax,
1235                      Float_t rmin,Float_t rmax,Float_t zmax)
1236 {
1237   //
1238   // Generates lego plots of:
1239   //    - radiation length map phi vs theta
1240   //    - radiation length map phi vs eta
1241   //    - interaction length map
1242   //    - g/cm2 length map
1243   //
1244   //  ntheta    bins in theta, eta
1245   //  themin    minimum angle in theta (degrees)
1246   //  themax    maximum angle in theta (degrees)
1247   //  nphi      bins in phi
1248   //  phimin    minimum angle in phi (degrees)
1249   //  phimax    maximum angle in phi (degrees)
1250   //  rmin      minimum radius
1251   //  rmax      maximum radius
1252   //  
1253   //
1254   //  The number of events generated = ntheta*nphi
1255   //  run input parameters in macro setup (default="Config.C")
1256   //
1257   //  Use macro "lego.C" to visualize the 3 lego plots in spherical coordinates
1258   //Begin_Html
1259   /*
1260     <img src="gif/AliRunLego1.gif">
1261   */
1262   //End_Html
1263   //Begin_Html
1264   /*
1265     <img src="gif/AliRunLego2.gif">
1266   */
1267   //End_Html
1268   //Begin_Html
1269   /*
1270     <img src="gif/AliRunLego3.gif">
1271   */
1272   //End_Html
1273   //
1274
1275   // check if initialisation has been done
1276   if (!fInitDone) Init(setup);
1277   
1278   fLego = new AliLego("lego","lego");
1279   fLego->Init(ntheta,themin,themax,nphi,phimin,phimax,rmin,rmax,zmax);
1280   fLego->Run();
1281   
1282   // Create only the Root event Tree
1283   gAlice->MakeTree("E");
1284   
1285   // End of this run, close files
1286   gAlice->FinishRun();
1287 }
1288
1289 //_____________________________________________________________________________
1290 void AliRun::SetCurrentTrack(Int_t track)
1291
1292   //
1293   // Set current track number
1294   //
1295   fCurrent = track; 
1296 }
1297  
1298 //_____________________________________________________________________________
1299 void AliRun::SetTrack(Int_t done, Int_t parent, Int_t ipart, Float_t *pmom,
1300                       Float_t *vpos, Float_t *polar, Float_t tof,
1301                       const char *mecha, Int_t &ntr, Float_t weight)
1302
1303   //
1304   // Load a track on the stack
1305   //
1306   // done     0 if the track has to be transported
1307   //          1 if not
1308   // parent   identifier of the parent track. -1 for a primary
1309   // ipart    particle code
1310   // pmom     momentum GeV/c
1311   // vpos     position 
1312   // polar    polarisation 
1313   // tof      time of flight in seconds
1314   // mecha    production mechanism
1315   // ntr      on output the number of the track stored
1316   //
1317   TClonesArray &particles = *fParticles;
1318   GParticle *particle;
1319   Float_t mass;
1320   char pname[21];
1321   const Int_t firstchild=-1;
1322   const Int_t lastchild=-1;
1323   const Int_t KS=0;
1324   const Float_t tlife=0;
1325   
1326   AliMC::GetMC()->GetParticle(ipart,pname,mass);
1327   Float_t e=TMath::Sqrt(mass*mass+pmom[0]*pmom[0]+
1328                         pmom[1]*pmom[1]+pmom[2]*pmom[2]);
1329   
1330   //printf("Loading particle %s mass %f ene %f No %d ip %d pos %f %f %f mom %f %f %f KS %d m %s\n",
1331   //pname,mass,e,fNtrack,ipart,vpos[0],vpos[1],vpos[2],pmom[0],pmom[1],pmom[2],KS,mecha);
1332   
1333   particle=new(particles[fNtrack]) GParticle(KS,ipart,parent,firstchild,
1334                                              lastchild,pmom[0],pmom[1],pmom[2],
1335                                              e,mass,vpos[0],vpos[1],vpos[2],
1336                                              polar[0],polar[1],polar[2],tof,
1337                                              tlife,mecha,weight);
1338   if(!done) particle->SetBit(Done_Bit);
1339   
1340   if(parent>=0) {
1341     particle=(GParticle*) fParticles->UncheckedAt(parent);
1342     particle->SetLastChild(fNtrack);
1343     if(particle->GetFirstChild()<0) particle->SetFirstChild(fNtrack);
1344   } else { 
1345     //
1346     // This is a primary track. Set high water mark for this event
1347     fHgwmk=fNtrack;
1348     //
1349     // Set also number if primary tracks
1350     fHeader.SetNprimary(fHgwmk+1);
1351     fHeader.SetNtrack(fHgwmk+1);
1352   }
1353   ntr = fNtrack++;
1354 }
1355
1356 //_____________________________________________________________________________
1357 void AliRun::KeepTrack(const Int_t track)
1358
1359   //
1360   // flags a track to be kept
1361   //
1362   TClonesArray &particles = *fParticles;
1363   ((GParticle*)particles[track])->SetBit(Keep_Bit);
1364 }
1365  
1366 //_____________________________________________________________________________
1367 void AliRun::StepManager(Int_t id) const
1368 {
1369   //
1370   // Called at every step during transport
1371   //
1372
1373   AliMC* pMC = AliMC::GetMC();
1374
1375   Int_t copy;
1376   //
1377   // --- If lego option, do it and leave 
1378   if (fLego) {
1379     fLego->StepManager();
1380     return;
1381   }
1382   //Update energy deposition tables
1383   sEventEnergy[pMC->CurrentVol(0,copy)]+=pMC->Edep();
1384   
1385   //Call the appropriate stepping routine;
1386   AliModule *det = (AliModule*)fModules->At(id);
1387   if(det) det->StepManager();
1388 }
1389
1390 //_____________________________________________________________________________
1391 void AliRun::ReadEuclid(const char* filnam, Int_t id_det, const char* topvol)
1392 {
1393   //                                                                     
1394   //       read in the geometry of the detector in euclid file format    
1395   //                                                                     
1396   //        id_det : the detector identification (2=its,...)            
1397   //        topvol : return parameter describing the name of the top    
1398   //        volume of geometry.                                          
1399   //                                                                     
1400   //            author : m. maire                                        
1401   //                                                                     
1402   //     28.07.98
1403   //     several changes have been made by miroslav helbich
1404   //     subroutine is rewrited to follow the new established way of memory
1405   //     booking for tracking medias and rotation matrices.
1406   //     all used tracking media have to be defined first, for this you can use
1407   //     subroutine  greutmed.
1408   //     top volume is searched as only volume not positioned into another 
1409   //
1410
1411   AliMC* pMC = AliMC::GetMC();
1412
1413   Int_t i, nvol, iret, itmed, irot, numed, npar, ndiv, iaxe;
1414   Int_t ndvmx, nr, flag;
1415   char key[5], card[77], natmed[21];
1416   char name[5], mother[5], shape[5], konly[5], volst[7000][5];
1417   char *filtmp;
1418   Float_t par[50];
1419   Float_t teta1, phi1, teta2, phi2, teta3, phi3, orig, step;
1420   Float_t xo, yo, zo;
1421   Int_t idrot[5000],istop[7000];
1422   FILE *lun;
1423   AliModule *det;
1424   //
1425   TObjArray &dets = *fModules;
1426   if(!dets[id_det]) {
1427     printf(" *** GREUTMED *** Detector %d not defined\n",id_det);
1428     return;
1429   } else {
1430     det = (AliModule*) dets[id_det];
1431   }
1432   //
1433   // *** The input filnam name will be with extension '.euc'
1434   filtmp=gSystem->ExpandPathName(filnam);
1435   lun=fopen(filtmp,"r");
1436   delete [] filtmp;
1437   if(!lun) {
1438     printf(" *** GREUCL *** Could not open file %s\n",filnam);
1439     return;
1440   }
1441   //* --- definition of rotation matrix 0 ---
1442   idrot[0]=0;
1443   nvol=0;
1444  L10:
1445   for(i=0;i<77;i++) card[i]=0;
1446   iret=fscanf(lun,"%77[^\n]",card);
1447   if(iret<=0) goto L20;
1448   fscanf(lun,"%*c");
1449   //*
1450   strncpy(key,card,4);
1451   key[4]='\0';
1452   if (!strcmp(key,"TMED")) {
1453     sscanf(&card[5],"%d '%[^']'",&itmed,natmed);
1454     //Pad the string with blanks
1455     i=-1;
1456     while(natmed[++i]);
1457     while(i<20) natmed[i++]=' ';
1458     natmed[i]='\0';
1459     //
1460     pMC->Gckmat(fIdtmed[itmed+id_det*100-1],natmed);
1461     //*
1462   } else if (!strcmp(key,"ROTM")) {
1463     sscanf(&card[4],"%d %f %f %f %f %f %f",&irot,&teta1,&phi1,&teta2,&phi2,&teta3,&phi3);
1464     det->AliMatrix(idrot[irot],teta1,phi1,teta2,phi2,teta3,phi3);
1465     //*
1466   } else if (!strcmp(key,"VOLU")) {
1467     sscanf(&card[5],"'%[^']' '%[^']' %d %d", name, shape, &numed, &npar);
1468     if (npar>0) {
1469       for(i=0;i<npar;i++) fscanf(lun,"%f",&par[i]);
1470       fscanf(lun,"%*c");
1471     }
1472     pMC->Gsvolu( name, shape, fIdtmed[numed+id_det*100-1], par, npar);
1473     //*     save the defined volumes
1474     strcpy(volst[++nvol],name);
1475     istop[nvol]=1;
1476     //*
1477   } else if (!strcmp(key,"DIVN")) {
1478     sscanf(&card[5],"'%[^']' '%[^']' %d %d", name, mother, &ndiv, &iaxe);
1479     pMC->Gsdvn  ( name, mother, ndiv, iaxe );
1480     //*
1481   } else if (!strcmp(key,"DVN2")) {
1482     sscanf(&card[5],"'%[^']' '%[^']' %d %d %f %d",name, mother, &ndiv, &iaxe, &orig, &numed);
1483     pMC->Gsdvn2( name, mother, ndiv, iaxe, orig,fIdtmed[numed+id_det*100-1]);
1484     //*
1485   } else if (!strcmp(key,"DIVT")) {
1486     sscanf(&card[5],"'%[^']' '%[^']' %f %d %d %d", name, mother, &step, &iaxe, &numed, &ndvmx);
1487     pMC->Gsdvt ( name, mother, step, iaxe, fIdtmed[numed+id_det*100-1], ndvmx);
1488     //*
1489   } else if (!strcmp(key,"DVT2")) {
1490     sscanf(&card[5],"'%[^']' '%[^']' %f %d %f %d %d", name, mother, &step, &iaxe, &orig, &numed, &ndvmx);
1491     pMC->Gsdvt2 ( name, mother, step, iaxe, orig, fIdtmed[numed+id_det*100-1], ndvmx );
1492     //*
1493   } else if (!strcmp(key,"POSI")) {
1494     sscanf(&card[5],"'%[^']' %d '%[^']' %f %f %f %d '%[^']'", name, &nr, mother, &xo, &yo, &zo, &irot, konly);
1495     //*** volume name cannot be the top volume
1496     for(i=1;i<=nvol;i++) {
1497       if (!strcmp(volst[i],name)) istop[i]=0;
1498     }
1499     //*
1500     pMC->Gspos  ( name, nr, mother, xo, yo, zo, idrot[irot], konly );
1501     //*
1502   } else if (!strcmp(key,"POSP")) {
1503     sscanf(&card[5],"'%[^']' %d '%[^']' %f %f %f %d '%[^']' %d", name, &nr, mother, &xo, &yo, &zo, &irot, konly, &npar);
1504     if (npar > 0) {
1505       for(i=0;i<npar;i++) fscanf(lun,"%f",&par[i]);
1506       fscanf(lun,"%*c");
1507     }
1508     //*** volume name cannot be the top volume
1509     for(i=1;i<=nvol;i++) {
1510       if (!strcmp(volst[i],name)) istop[i]=0;
1511     }
1512     //*
1513     pMC->Gsposp ( name, nr, mother, xo,yo,zo, idrot[irot], konly, par, npar);
1514   }
1515   //*
1516   if (strcmp(key,"END")) goto L10;
1517   //* find top volume in the geometry
1518   flag=0;
1519   for(i=1;i<=nvol;i++) {
1520     if (istop[i] && flag) {
1521       printf(" *** GREUCL *** warning: %s is another possible top volume\n",volst[i]);
1522     }
1523     if (istop[i] && !flag) {
1524       topvol=volst[i];
1525       printf(" *** GREUCL *** volume %s taken as a top volume\n",topvol);
1526       flag=1;
1527     }
1528   }
1529   if (!flag) {
1530     printf("*** GREUCL *** warning: top volume not found\n");
1531   }
1532   fclose (lun);
1533   //*
1534   //*     commented out only for the not cernlib version
1535   printf(" *** GREUCL *** file: %s is now read in\n",filnam);
1536   //
1537   return;
1538   //*
1539   L20:
1540   printf(" *** GREUCL *** reading error or premature end of file\n");
1541 }
1542
1543 //_____________________________________________________________________________
1544 void AliRun::ReadEuclidMedia(const char* filnam, Int_t id_det)
1545 {
1546   //                                                                     
1547   //       read in the materials and tracking media for the detector     
1548   //                   in euclid file format                             
1549   //                                                                     
1550   //       filnam: name of the input file                                
1551   //       id_det: id_det is the detector identification (2=its,...)     
1552   //                                                                     
1553   //            author : miroslav helbich                                
1554   //
1555   Float_t sxmgmx = gAlice->Field()->Max();
1556   Int_t   isxfld = gAlice->Field()->Integ();
1557   Int_t end, i, iret, itmed;
1558   char key[5], card[130], natmed[21], namate[21];
1559   Float_t ubuf[50];
1560   char* filtmp;
1561   FILE *lun;
1562   Int_t imate;
1563   Int_t nwbuf, isvol, ifield, nmat;
1564   Float_t a, z, dens, radl, absl, fieldm, tmaxfd, stemax, deemax, epsil, stmin;
1565   AliModule* det;
1566 //
1567   TObjArray &dets = *fModules;
1568   if(!dets[id_det]) {
1569     printf(" *** GREUTMED *** Detector %d not defined\n",id_det);
1570     return;
1571   } else {
1572     det = (AliModule*) dets[id_det];
1573   }
1574   end=strlen(filnam);
1575   for(i=0;i<end;i++) if(filnam[i]=='.') {
1576     end=i;
1577     break;
1578   }
1579   //
1580   // *** The input filnam name will be with extension '.euc'
1581   printf("The file name is %s\n",filnam); //Debug
1582   filtmp=gSystem->ExpandPathName(filnam);
1583   lun=fopen(filtmp,"r");
1584   delete [] filtmp;
1585   if(!lun) {
1586     printf(" *** GREUTMED *** Could not open file %s\n",filnam);
1587     return;
1588   }
1589   //
1590   // Retrieve Mag Field parameters
1591   Int_t ISXFLD=gAlice->Field()->Integ();
1592   Float_t SXMGMX=gAlice->Field()->Max();
1593   //
1594  L10:
1595   for(i=0;i<130;i++) card[i]=0;
1596   iret=fscanf(lun,"%4s %[^\n]",key,card);
1597   if(iret<=0) goto L20;
1598   fscanf(lun,"%*c");
1599   //*
1600   //* read material
1601   if (!strcmp(key,"MATE")) {
1602     sscanf(card,"%d '%[^']' %f %f %f %f %f %d",&imate,namate,&a,&z,&dens,&radl,&absl,&nwbuf);
1603     if (nwbuf>0) for(i=0;i<nwbuf;i++) fscanf(lun,"%f",&ubuf[i]);
1604     //Pad the string with blanks
1605     i=-1;
1606     while(namate[++i]);
1607     while(i<20) namate[i++]=' ';
1608     namate[i]='\0';
1609     //
1610     det->AliMaterial(imate,namate,a,z,dens,radl,absl,ubuf,nwbuf);
1611     //* read tracking medium
1612   } else if (!strcmp(key,"TMED")) {
1613     sscanf(card,"%d '%[^']' %d %d %d %f %f %f %f %f %f %d",
1614            &itmed,natmed,&nmat,&isvol,&ifield,&fieldm,&tmaxfd,
1615            &stemax,&deemax,&epsil,&stmin,&nwbuf);
1616     if (nwbuf>0) for(i=0;i<nwbuf;i++) fscanf(lun,"%f",&ubuf[i]);
1617     if (ifield<0) ifield=isxfld;
1618     if (fieldm<0) fieldm=sxmgmx;
1619     //Pad the string with blanks
1620     i=-1;
1621     while(natmed[++i]);
1622     while(i<20) natmed[i++]=' ';
1623     natmed[i]='\0';
1624     //
1625     det->AliMedium(itmed+id_det*100,natmed,nmat,isvol,ISXFLD,SXMGMX,tmaxfd,
1626                    stemax,deemax,epsil,stmin,ubuf,nwbuf);
1627     (*fImedia)[fIdtmed[itmed+id_det*100-1]-1]=id_det;
1628     //*
1629   }
1630   //*
1631   if (strcmp(key,"END")) goto L10;
1632   fclose (lun);
1633   //*
1634   //*     commented out only for the not cernlib version
1635   printf(" *** GREUTMED *** file: %s is now read in\n",filnam);
1636   //*
1637   return;
1638   //*
1639  L20:
1640   printf(" *** GREUTMED *** reading error or premature end of file\n");
1641
1642  
1643 //_____________________________________________________________________________
1644 void AliRun::Streamer(TBuffer &R__b)
1645 {
1646   //
1647   // Stream an object of class AliRun.
1648   //
1649   if (R__b.IsReading()) {
1650     Version_t R__v = R__b.ReadVersion(); if (R__v) { }
1651     TNamed::Streamer(R__b);
1652     if (!gAlice) gAlice = this;
1653     gROOT->GetListOfBrowsables()->Add(this,"Run");
1654     R__b >> fNtrack;
1655     R__b >> fHgwmk;
1656     R__b >> fDebug;
1657     fHeader.Streamer(R__b);
1658     R__b >> fModules;
1659     R__b >> fParticles;
1660     R__b >> fField; 
1661     //    R__b >> fMC;
1662     R__b >> fNdets;
1663     R__b >> fTrRmax;
1664     R__b >> fTrZmax;
1665     R__b >> fGenerator;
1666   } else {
1667     R__b.WriteVersion(AliRun::IsA());
1668     TNamed::Streamer(R__b);
1669     R__b << fNtrack;
1670     R__b << fHgwmk;
1671     R__b << fDebug;
1672     fHeader.Streamer(R__b);
1673     R__b << fModules;
1674     R__b << fParticles;
1675     R__b << fField;
1676     //    R__b << fMC;
1677     R__b << fNdets;
1678     R__b << fTrRmax;
1679     R__b << fTrZmax;
1680     R__b << fGenerator;
1681   }
1682
1683
1684
1685 //_____________________________________________________________________________
1686 //
1687 //                 Interfaces to Fortran
1688 //
1689 //_____________________________________________________________________________
1690
1691 extern "C" void type_of_call  rxgtrak (Int_t &mtrack, Int_t &ipart, Float_t *pmom, 
1692                                        Float_t &e, Float_t *vpos, Float_t &tof)
1693 {
1694   //
1695   //     Fetches next track from the ROOT stack for transport. Called by the
1696   //     modified version of GTREVE.
1697   //
1698   //              Track number in the ROOT stack. If MTRACK=0 no
1699   //      mtrack  more tracks are left in the stack to be
1700   //              transported.
1701   //      ipart   Particle code in the GEANT conventions.
1702   //      pmom[3] Particle momentum in GeV/c
1703   //      e       Particle energy in GeV
1704   //      vpos[3] Particle position
1705   //      tof     Particle time of flight in seconds
1706   //
1707   Float_t polar[3];
1708   gAlice->GetNextTrack(mtrack, ipart, pmom, e, vpos, polar, tof);
1709   mtrack++;
1710 }
1711
1712 //_____________________________________________________________________________
1713 extern "C" void type_of_call 
1714 #ifndef WIN32
1715 rxstrak (Int_t &keep, Int_t &parent, Int_t &ipart, Float_t *pmom, 
1716                Float_t *vpos, Float_t &tof, const char* cmech, Int_t &ntr, const int cmlen)
1717 #else
1718 rxstrak (Int_t &keep, Int_t &parent, Int_t &ipart, Float_t *pmom,
1719          Float_t *vpos, Float_t &tof, const char* cmech, const int cmlen,
1720          Int_t &ntr)
1721 #endif
1722 {
1723   //
1724   //     Fetches next track from the ROOT stack for transport. Called by GUKINE
1725   //     and GUSTEP.
1726   //
1727   //              Status of the track. If keep=0 the track is put
1728   //      keep    on the ROOT stack but it is not fetched for
1729   //              transport.
1730   //      parent  Parent track. If parent=0 the track is a primary.
1731   //              In GUSTEP the routine is normally called to store
1732   //              secondaries generated by the current track whose
1733   //              ROOT stack number is MTRACK (common SCKINE.
1734   //      ipart   Particle code in the GEANT conventions.
1735   //      pmom[3] Particle momentum in GeV/c
1736   //      vpos[3] Particle position
1737   //      tof     Particle time of flight in seconds
1738   //
1739   //      cmech   (CHARACTER*10) Particle origin. This field is user
1740   //              defined and it is not used inside the GALICE code.
1741   //      ntr     Number assigned to the particle in the ROOT stack.
1742   //
1743   char mecha[11];
1744   Float_t polar[3]={0.,0.,0.};
1745   for(int i=0; i<10 && i<cmlen; i++) mecha[i]=cmech[i];
1746   mecha[10]=0;
1747   gAlice->SetTrack(keep, parent-1, ipart, pmom, vpos, polar, tof, mecha, ntr);
1748   ntr++;
1749 }
1750
1751 //_____________________________________________________________________________
1752 extern "C" void type_of_call  rxkeep(const Int_t &n)
1753 {
1754   if( NULL==gAlice ) exit(1);
1755   
1756   if( n<=0 || n>gAlice->Particles()->GetEntries() )
1757     {
1758       printf("  Bad index n=%d must be 0<n<=%d\n",
1759              n,gAlice->Particles()->GetEntries());
1760       exit(1);
1761     }
1762   
1763   ((GParticle*)(gAlice->Particles()->UncheckedAt(n-1)))->SetBit(Keep_Bit);
1764 }
1765
1766 //_____________________________________________________________________________
1767 extern "C" void type_of_call  rxouth ()
1768 {
1769   //
1770   // Called by Gtreve at the end of each primary track
1771   //
1772   gAlice->FinishPrimary();
1773 }
1774