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