]> git.uio.no Git - u/mrichter/AliRoot.git/blob - STEER/AliRun.cxx
remove the dummy argument in fStack->GetEvent call
[u/mrichter/AliRoot.git] / STEER / AliRun.cxx
1 /**************************************************************************
2  * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
3  *                                                                        *
4  * Author: The ALICE Off-line Project.                                    *
5  * Contributors are mentioned in the code where appropriate.              *
6  *                                                                        *
7  * Permission to use, copy, modify and distribute this software and its   *
8  * documentation strictly for non-commercial purposes is hereby granted   *
9  * without fee, provided that the above copyright notice appears in all   *
10  * copies and that both the copyright notice and this permission notice   *
11  * appear in the supporting documentation. The authors make no claims     *
12  * about the suitability of this software for any purpose. It is          *
13  * provided "as is" without express or implied warranty.                  *
14  **************************************************************************/
15
16 /*
17 $Log$
18 Revision 1.72  2001/07/03 08:10:57  hristov
19 J.Chudoba's changes merged correctly with the HEAD
20
21 Revision 1.70  2001/06/29 08:01:36  morsch
22 Small correction to the previous.
23
24 Revision 1.69  2001/06/28 16:27:50  morsch
25 AliReco() with user control of event range.
26
27 Revision 1.68  2001/06/11 13:14:40  morsch
28 SetAliGenEventHeader() method added.
29
30 Revision 1.67  2001/06/07 18:24:50  buncic
31 Removed compilation warning in AliConfig initialisation.
32
33 Revision 1.66  2001/05/22 14:32:40  hristov
34 Weird inline removed
35
36 Revision 1.65  2001/05/21 17:22:51  buncic
37 Fixed problem with missing AliConfig while reading galice.root
38
39 Revision 1.64  2001/05/16 14:57:22  alibrary
40 New files for folders and Stack
41
42 Revision 1.62  2001/04/06 11:12:33  morsch
43 Clear fParticles after each event. (Ivana Hrivnacova)
44
45 Revision 1.61  2001/03/30 07:04:10  morsch
46 Call fGenerator->FinishRun() for final print-outs, cross-section and weight calculations.
47
48 Revision 1.60  2001/03/21 18:22:30  hristov
49 fParticleFileMap fix (I.Hrivnacova)
50
51 Revision 1.59  2001/03/12 17:47:03  hristov
52 Changes needed on Sun with CC 5.0
53
54 Revision 1.58  2001/03/09 14:27:26  morsch
55 Fix for multiple events per file: inhibit decrease of size of  fParticleFileMap.
56
57 Revision 1.57  2001/02/23 17:40:23  buncic
58 All trees needed for simulation created in RunMC(). TreeR and its branches
59 are now created in new RunReco() method.
60
61 Revision 1.56  2001/02/14 15:45:20  hristov
62 Algorithmic way of getting entry index in fParticleMap. Protection of fParticleFileMap (I.Hrivnacova)
63
64 Revision 1.55  2001/02/12 15:52:54  buncic
65 Removed OpenBaseFile().
66
67 Revision 1.54  2001/02/07 10:39:05  hristov
68 Remove default value for argument
69
70 Revision 1.53  2001/02/06 11:02:26  hristov
71 New SetTrack interface added, added check for unfilled particles in FinishEvent (I.Hrivnacova)
72
73 Revision 1.52  2001/02/05 16:22:25  buncic
74 Added TreeS to GetEvent().
75
76 Revision 1.51  2001/02/02 15:16:20  morsch
77 SetHighWaterMark method added to mark last particle in event.
78
79 Revision 1.50  2001/01/27 10:32:00  hristov
80 Leave the loop when primaries are filled (I.Hrivnacova)
81
82 Revision 1.49  2001/01/26 19:58:48  hristov
83 Major upgrade of AliRoot code
84
85 Revision 1.48  2001/01/17 10:50:50  hristov
86 Corrections to destructors
87
88 Revision 1.47  2000/12/18 10:44:01  morsch
89 Possibility to set field map by passing pointer to objet of type AliMagF via
90 SetField().
91 Example:
92 gAlice->SetField(new AliMagFCM("Map2", "$(ALICE_ROOT)/data/field01.dat",2,1.,10.));
93
94 Revision 1.46  2000/12/14 19:29:27  fca
95 galice.cuts was not read any more
96
97 Revision 1.45  2000/11/30 07:12:49  alibrary
98 Introducing new Rndm and QA classes
99
100 Revision 1.44  2000/10/26 13:58:59  morsch
101 Add possibility to choose the lego generator (of type AliGeneratorLego or derived) when running
102 RunLego(). Default is the base class AliGeneratorLego.
103
104 Revision 1.43  2000/10/09 09:43:17  fca
105 Special remapping of hits for TPC and TRD. End-of-primary action introduced
106
107 Revision 1.42  2000/10/02 21:28:14  fca
108 Removal of useless dependecies via forward declarations
109
110 Revision 1.41  2000/07/13 16:19:09  fca
111 Mainly coding conventions + some small bug fixes
112
113 Revision 1.40  2000/07/12 08:56:25  fca
114 Coding convention correction and warning removal
115
116 Revision 1.39  2000/07/11 18:24:59  fca
117 Coding convention corrections + few minor bug fixes
118
119 Revision 1.38  2000/06/20 13:05:45  fca
120 Writing down the TREE headers before job starts
121
122 Revision 1.37  2000/06/09 20:05:11  morsch
123 Introduce possibility to chose magnetic field version 3: AliMagFDM + field02.dat
124
125 Revision 1.36  2000/06/08 14:03:58  hristov
126 Only one initializer for a default argument
127
128 Revision 1.35  2000/06/07 10:13:14  hristov
129 Delete only existent objects.
130
131 Revision 1.34  2000/05/18 10:45:38  fca
132 Delete Particle Factory properly
133
134 Revision 1.33  2000/05/16 13:10:40  fca
135 New method IsNewTrack and fix for a problem in Father-Daughter relations
136
137 Revision 1.32  2000/04/27 10:38:21  fca
138 Correct termination of Lego Run and introduce Lego getter in AliRun
139
140 Revision 1.31  2000/04/26 10:17:32  fca
141 Changes in Lego for G4 compatibility
142
143 Revision 1.30  2000/04/18 19:11:40  fca
144 Introduce variable Config.C function signature
145
146 Revision 1.29  2000/04/07 11:12:34  fca
147 G4 compatibility changes
148
149 Revision 1.28  2000/04/05 06:51:06  fca
150 Workaround for an HP compiler problem
151
152 Revision 1.27  2000/03/22 18:08:07  fca
153 Rationalisation of the virtual MC interfaces
154
155 Revision 1.26  2000/03/22 13:42:26  fca
156 SetGenerator does not replace an existing generator, ResetGenerator does
157
158 Revision 1.25  2000/02/23 16:25:22  fca
159 AliVMC and AliGeant3 classes introduced
160 ReadEuclid moved from AliRun to AliModule
161
162 Revision 1.24  2000/01/19 17:17:20  fca
163 Introducing a list of lists of hits -- more hits allowed for detector now
164
165 Revision 1.23  1999/12/03 11:14:31  fca
166 Fixing previous wrong checking
167
168 Revision 1.21  1999/11/25 10:40:08  fca
169 Fixing daughters information also in primary tracks
170
171 Revision 1.20  1999/10/04 18:08:49  fca
172 Adding protection against inconsistent Euclid files
173
174 Revision 1.19  1999/09/29 07:50:40  fca
175 Introduction of the Copyright and cvs Log
176
177 */
178
179 ///////////////////////////////////////////////////////////////////////////////
180 //                                                                           //
181 //  Control class for Alice C++                                              //
182 //  Only one single instance of this class exists.                           //
183 //  The object is created in main program aliroot                            //
184 //  and is pointed by the global gAlice.                                     //
185 //                                                                           //
186 //   -Supports the list of all Alice Detectors (fModules).                 //
187 //   -Supports the list of particles (fParticles).                           //
188 //   -Supports the Trees.                                                    //
189 //   -Supports the geometry.                                                 //
190 //   -Supports the event display.                                            //
191 //Begin_Html
192 /*
193 <img src="picts/AliRunClass.gif">
194 */
195 //End_Html
196 //Begin_Html
197 /*
198 <img src="picts/alirun.gif">
199 */
200 //End_Html
201 //                                                                           //
202 ///////////////////////////////////////////////////////////////////////////////
203
204 #include <stdlib.h>
205 #include <stdio.h>
206 #include <string.h>
207 #include <iostream.h>
208  
209 #include <TFile.h>
210 #include <TRandom.h>
211 #include <TBRIK.h> 
212 #include <TCint.h> 
213 #include <TSystem.h>
214 #include <TObjectTable.h>
215 #include <TTree.h>
216 #include <TGeometry.h>
217 #include <TROOT.h>
218 #include <TBrowser.h>
219 #include <TFolder.h>
220 #include <TNode.h>
221
222 #include "TParticle.h"
223 #include "AliRun.h"
224 #include "AliDisplay.h"
225 #include "AliMC.h"
226 #include "AliLego.h"
227 #include "AliMagFC.h"
228 #include "AliMagFCM.h"
229 #include "AliMagFDM.h"
230 #include "AliHit.h"
231 #include "TRandom3.h"
232 #include "AliMCQA.h"
233 #include "AliGenerator.h"
234 #include "AliLegoGenerator.h"
235 #include "AliConfig.h"
236 #include "AliStack.h"
237 #include "AliGenEventHeader.h"
238 #include "AliHeader.h"
239
240 #include "AliDetector.h"
241
242 AliRun *gAlice;
243
244 ClassImp(AliRun)
245
246 //_____________________________________________________________________________
247 AliRun::AliRun()
248 {
249   //
250   // Default constructor for AliRun
251   //
252   fHeader    = 0;
253   fRun       = 0;
254   fEvent     = 0;
255   fStack     = 0;
256   fModules   = 0;
257   fGenerator = 0;
258   fTreeD     = 0;
259   fTreeH     = 0;
260   fTreeE     = 0;
261   fTreeR     = 0;
262   fTreeS     = 0;
263   fGeometry  = 0;
264   fDisplay   = 0;
265   fField     = 0;
266   fMC        = 0;
267   fNdets     = 0;
268   fImedia    = 0;
269   fTrRmax    = 1.e10;
270   fTrZmax    = 1.e10;
271   fInitDone  = kFALSE;
272   fLego      = 0;
273   fPDGDB     = 0;        //Particle factory object!
274   fHitLists  = 0;
275   fConfigFunction    = "\0";
276   fRandom = 0;
277   fMCQA = 0;
278   fTransParName = "\0";
279   fBaseFileName = ".\0";
280   fDebug        = 0;
281 }
282
283 //_____________________________________________________________________________
284 AliRun::AliRun(const char *name, const char *title)
285   : TNamed(name,title)
286 {
287   //
288   //  Constructor for the main processor.
289   //  Creates the geometry
290   //  Creates the list of Detectors.
291   //  Creates the list of particles.
292   //
293   Int_t i;
294   
295   gAlice     = this;
296   fTreeD     = 0;
297   fTreeH     = 0;
298   fTreeE     = 0;
299   fTreeR     = 0;
300   fTreeS     = 0;
301   fTrRmax    = 1.e10;
302   fTrZmax    = 1.e10;
303   fGenerator = 0;
304   fInitDone  = kFALSE;
305   fLego      = 0;
306   fField     = 0;
307   fConfigFunction    = "Config();";
308
309   // Set random number generator
310   gRandom = fRandom = new TRandom3();
311
312   if (gSystem->Getenv("CONFIG_SEED")) {
313      gRandom->SetSeed((UInt_t)atoi(gSystem->Getenv("CONFIG_SEED")));
314   }
315   
316   gROOT->GetListOfBrowsables()->Add(this,name);
317   //
318   // Particle stack
319   fStack = new AliStack(10000);
320   // create the support list for the various Detectors
321   fModules = new TObjArray(77);
322   //
323   // Create the TNode geometry for the event display
324   
325   BuildSimpleGeometry();
326   
327   fHeader    = new AliHeader();
328   fRun       = 0;
329   fEvent     = 0;
330   //
331   fDisplay = 0;
332   //
333   // Create default mag field
334   SetField();
335   //
336   fMC      = gMC;
337   //
338   // Prepare the tracking medium lists
339   fImedia = new TArrayI(1000);
340   for(i=0;i<1000;i++) (*fImedia)[i]=-99;
341   //
342   // Make particles
343   fPDGDB     = TDatabasePDG::Instance();        //Particle factory object!
344
345   AliConfig::Instance()->Add(fPDGDB); 
346   //
347   // Create HitLists list
348   fHitLists  = new TList();
349   //
350   SetTransPar();
351   fBaseFileName = ".\0";
352   //
353   fDebug        = 0;
354 }
355
356
357 //_____________________________________________________________________________
358 AliRun::~AliRun()
359 {
360   //
361   // Default AliRun destructor
362   //
363   delete fImedia;
364   delete fField;
365   delete fMC;
366   delete fGeometry;
367   delete fDisplay;
368   delete fGenerator;
369   delete fLego;
370   delete fTreeD;
371   delete fTreeH;
372   delete fTreeE;
373   delete fTreeR;
374   delete fTreeS;
375   if (fModules) {
376     fModules->Delete();
377     delete fModules;
378   }
379   delete fStack;
380   delete fHitLists;
381   delete fPDGDB;
382   delete fMCQA;
383   delete fHeader;
384 }
385
386 //_____________________________________________________________________________
387 void AliRun::AddHit(Int_t id, Int_t track, Int_t *vol, Float_t *hits) const
388 {
389   //
390   //  Add a hit to detector id
391   //
392   TObjArray &dets = *fModules;
393   if(dets[id]) ((AliModule*) dets[id])->AddHit(track,vol,hits);
394 }
395
396 //_____________________________________________________________________________
397 void AliRun::AddDigit(Int_t id, Int_t *tracks, Int_t *digits) const
398 {
399   //
400   // Add digit to detector id
401   //
402   TObjArray &dets = *fModules;
403   if(dets[id]) ((AliModule*) dets[id])->AddDigit(tracks,digits);
404 }
405
406 //_____________________________________________________________________________
407 void AliRun::Browse(TBrowser *b)
408 {
409   //
410   // Called when the item "Run" is clicked on the left pane
411   // of the Root browser.
412   // It displays the Root Trees and all detectors.
413   //
414   if(!fStack) fStack=fHeader->Stack();
415   TTree*  pTreeK = fStack->TreeK();
416     
417   if (pTreeK) b->Add(pTreeK,pTreeK->GetName());
418   if (fTreeH) b->Add(fTreeH,fTreeH->GetName());
419   if (fTreeD) b->Add(fTreeD,fTreeD->GetName());
420   if (fTreeE) b->Add(fTreeE,fTreeE->GetName());
421   if (fTreeR) b->Add(fTreeR,fTreeR->GetName());
422   if (fTreeS) b->Add(fTreeS,fTreeS->GetName());
423   
424   TIter next(fModules);
425   AliModule *detector;
426   while((detector = (AliModule*)next())) {
427     b->Add(detector,detector->GetName());
428   }
429   b->Add(fMCQA,"AliMCQA");
430 }
431
432 //_____________________________________________________________________________
433 void AliRun::Build()
434 {
435   //
436   // Initialize Alice geometry
437   // Dummy routine
438   //
439 }
440  
441 //_____________________________________________________________________________
442 void AliRun::BuildSimpleGeometry()
443 {
444   //
445   // Create a simple TNode geometry used by Root display engine
446   //
447   // Initialise geometry
448   //
449   fGeometry = new TGeometry("AliceGeom","Galice Geometry for Hits");
450   new TMaterial("void","Vacuum",0,0,0);  //Everything is void
451   TBRIK *brik = new TBRIK("S_alice","alice volume","void",2000,2000,3000);
452   brik->SetVisibility(0);
453   new TNode("alice","alice","S_alice");
454 }
455
456 //_____________________________________________________________________________
457 void AliRun::CleanDetectors()
458 {
459   //
460   // Clean Detectors at the end of event
461   //
462   TIter next(fModules);
463   AliModule *detector;
464   while((detector = (AliModule*)next())) {
465     detector->FinishEvent();
466   }
467 }
468
469 //_____________________________________________________________________________
470 Int_t AliRun::DistancetoPrimitive(Int_t, Int_t)
471 {
472   //
473   // Return the distance from the mouse to the AliRun object
474   // Dummy routine
475   //
476   return 9999;
477 }
478
479 //_____________________________________________________________________________
480 void AliRun::DumpPart (Int_t i) const
481 {
482   //
483   // Dumps particle i in the stack
484   //
485     fStack->DumpPart(i);
486 }
487
488 //_____________________________________________________________________________
489 void AliRun::DumpPStack () const
490 {
491   //
492   // Dumps the particle stack
493   //
494     fStack->DumpPStack();
495 }
496
497 //_____________________________________________________________________________
498 void  AliRun::SetField(AliMagF* magField)
499 {
500     // Set Magnetic Field Map
501     fField = magField;
502     fField->ReadField();
503 }
504
505 //_____________________________________________________________________________
506 void AliRun::SetField(Int_t type, Int_t version, Float_t scale,
507                       Float_t maxField, char* filename)
508 {
509   //
510   //  Set magnetic field parameters
511   //  type      Magnetic field transport flag 0=no field, 2=helix, 3=Runge Kutta
512   //  version   Magnetic field map version (only 1 active now)
513   //  scale     Scale factor for the magnetic field
514   //  maxField  Maximum value for the magnetic field
515
516   //
517   // --- Sanity check on mag field flags
518   if(fField) delete fField;
519   if(version==1) {
520     fField = new AliMagFC("Map1"," ",type,scale,maxField);
521   } else if(version<=2) {
522     fField = new AliMagFCM("Map2-3",filename,type,scale,maxField);
523     fField->ReadField();
524   } else if(version==3) {
525     fField = new AliMagFDM("Map4",filename,type,scale,maxField);
526     fField->ReadField();
527   } else {
528     Warning("SetField","Invalid map %d\n",version);
529   }
530 }
531  
532 //_____________________________________________________________________________
533 void AliRun::PreTrack()
534 {
535      TObjArray &dets = *fModules;
536      AliModule *module;
537
538      for(Int_t i=0; i<=fNdets; i++)
539        if((module = (AliModule*)dets[i]))
540          module->PreTrack();
541
542      fMCQA->PreTrack();
543 }
544
545 //_____________________________________________________________________________
546 void AliRun::PostTrack()
547 {
548      TObjArray &dets = *fModules;
549      AliModule *module;
550
551      for(Int_t i=0; i<=fNdets; i++)
552        if((module = (AliModule*)dets[i]))
553          module->PostTrack();
554 }
555
556 //_____________________________________________________________________________
557 void AliRun::FinishPrimary()
558 {
559   //
560   // Called  at the end of each primary track
561   //
562   
563   //  static Int_t count=0;
564   //  const Int_t times=10;
565   // This primary is finished, purify stack
566   fStack->PurifyKine();
567
568   TIter next(fModules);
569   AliModule *detector;
570   while((detector = (AliModule*)next())) {
571     detector->FinishPrimary();
572   }
573
574   // Write out hits if any
575   if (gAlice->TreeH()) {
576     gAlice->TreeH()->Fill();
577   }
578   
579   //
580   //  if(++count%times==1) gObjectTable->Print();
581 }
582
583 //_____________________________________________________________________________
584 void AliRun::BeginPrimary()
585 {
586   //
587   // Called  at the beginning of each primary track
588   //
589   
590   // Reset Hits info
591   gAlice->ResetHits();
592
593 }
594
595 //_____________________________________________________________________________
596 void AliRun::FinishEvent()
597 {
598   //
599   // Called at the end of the event.
600   //
601   
602   //
603   if(fLego) fLego->FinishEvent();
604
605   //Update the energy deposit tables
606   Int_t i;
607   for(i=0;i<fEventEnergy.GetSize();i++) {
608     fSummEnergy[i]+=fEventEnergy[i];
609     fSum2Energy[i]+=fEventEnergy[i]*fEventEnergy[i];
610   }
611
612
613   
614   // Update Header information 
615
616   fHeader->SetNprimary(fStack->GetNprimary());
617   fHeader->SetNtrack(fStack->GetNtrack());  
618
619   
620   // Write out the kinematics
621   fStack->FinishEvent();
622    
623   // Write out the event Header information
624   if (fTreeE) {
625       fHeader->SetStack(fStack);
626       fTreeE->Fill();
627   }
628   
629   
630   // Write Tree headers
631   TTree* pTreeK = fStack->TreeK();
632   if (pTreeK) pTreeK->Write(0,TObject::kOverwrite);
633   if (fTreeH) fTreeH->Write(0,TObject::kOverwrite);
634   
635   ++fEvent;
636 }
637
638 //_____________________________________________________________________________
639 void AliRun::FinishRun()
640 {
641   //
642   // Called at the end of the run.
643   //
644
645   //
646   if(fLego) fLego->FinishRun();
647   
648   // Clean detector information
649   TIter next(fModules);
650   AliModule *detector;
651   while((detector = (AliModule*)next())) {
652     detector->FinishRun();
653   }
654   
655   //Output energy summary tables
656   EnergySummary();
657
658   TFile *file = fTreeE->GetCurrentFile();
659
660   file->cd();
661   
662   fTreeE->Write(0,TObject::kOverwrite);
663   
664   // Write AliRun info and all detectors parameters
665   Write(0,TObject::kOverwrite);
666
667   // Clean tree information
668
669   fStack->FinishRun();
670   
671   if (fTreeH) {
672     delete fTreeH; fTreeH = 0;
673   }
674   if (fTreeD) {
675     delete fTreeD; fTreeD = 0;
676   }
677   if (fTreeR) {
678     delete fTreeR; fTreeR = 0;
679   }
680   if (fTreeE) {
681     delete fTreeE; fTreeE = 0;
682   }
683   if (fTreeS) {
684     delete fTreeS; fTreeS = 0;
685   }
686     
687   // Close output file
688   file->Write();
689 }
690
691 //_____________________________________________________________________________
692 void AliRun::FlagTrack(Int_t track)
693 {
694   // Delegate to stack
695   //
696     fStack->FlagTrack(track);
697 }
698  
699 //_____________________________________________________________________________
700 void AliRun::EnergySummary()
701 {
702   //
703   // Print summary of deposited energy
704   //
705
706   Int_t ndep=0;
707   Float_t edtot=0;
708   Float_t ed, ed2;
709   Int_t kn, i, left, j, id;
710   const Float_t kzero=0;
711   Int_t ievent=fHeader->GetEvent()+1;
712   //
713   // Energy loss information
714   if(ievent) {
715     printf("***************** Energy Loss Information per event (GEV) *****************\n");
716     for(kn=1;kn<fEventEnergy.GetSize();kn++) {
717       ed=fSummEnergy[kn];
718       if(ed>0) {
719         fEventEnergy[ndep]=kn;
720         if(ievent>1) {
721           ed=ed/ievent;
722           ed2=fSum2Energy[kn];
723           ed2=ed2/ievent;
724           ed2=100*TMath::Sqrt(TMath::Max(ed2-ed*ed,kzero))/ed;
725         } else 
726           ed2=99;
727         fSummEnergy[ndep]=ed;
728         fSum2Energy[ndep]=TMath::Min((Float_t) 99.,TMath::Max(ed2,kzero));
729         edtot+=ed;
730         ndep++;
731       }
732     }
733     for(kn=0;kn<(ndep-1)/3+1;kn++) {
734       left=ndep-kn*3;
735       for(i=0;i<(3<left?3:left);i++) {
736         j=kn*3+i;
737         id=Int_t (fEventEnergy[j]+0.1);
738         printf(" %s %10.3f +- %10.3f%%;",gMC->VolName(id),fSummEnergy[j],fSum2Energy[j]);
739       }
740       printf("\n");
741     }
742     //
743     // Relative energy loss in different detectors
744     printf("******************** Relative Energy Loss per event ********************\n");
745     printf("Total energy loss per event %10.3f GeV\n",edtot);
746     for(kn=0;kn<(ndep-1)/5+1;kn++) {
747       left=ndep-kn*5;
748       for(i=0;i<(5<left?5:left);i++) {
749         j=kn*5+i;
750         id=Int_t (fEventEnergy[j]+0.1);
751         printf(" %s %10.3f%%;",gMC->VolName(id),100*fSummEnergy[j]/edtot);
752       }
753       printf("\n");
754     }
755     for(kn=0;kn<75;kn++) printf("*"); 
756     printf("\n");
757   }
758   //
759   // Reset the TArray's
760   //  fEventEnergy.Set(0);
761   //  fSummEnergy.Set(0);
762   //  fSum2Energy.Set(0);
763 }
764
765 //_____________________________________________________________________________
766 AliModule *AliRun::GetModule(const char *name) const
767 {
768   //
769   // Return pointer to detector from name
770   //
771   return (AliModule*)fModules->FindObject(name);
772 }
773  
774 //_____________________________________________________________________________
775 AliDetector *AliRun::GetDetector(const char *name) const
776 {
777   //
778   // Return pointer to detector from name
779   //
780   return (AliDetector*)fModules->FindObject(name);
781 }
782  
783 //_____________________________________________________________________________
784 Int_t AliRun::GetModuleID(const char *name) const
785 {
786   //
787   // Return galice internal detector identifier from name
788   //
789   Int_t i=-1;
790   TObject *mod=fModules->FindObject(name);
791   if(mod) i=fModules->IndexOf(mod);
792   return i;
793 }
794  
795 //_____________________________________________________________________________
796 Int_t AliRun::GetEvent(Int_t event)
797 {
798   //
799   // Connect the Trees Kinematics and Hits for event # event
800   // Set branch addresses
801   //
802
803   // Reset existing structures
804   ResetHits();
805   ResetDigits();
806   ResetSDigits();
807   
808   // Delete Trees already connected
809   if (fTreeH) { delete fTreeH; fTreeH = 0;}
810   if (fTreeD) { delete fTreeD; fTreeD = 0;}
811   if (fTreeR) { delete fTreeR; fTreeR = 0;}
812   if (fTreeS) { delete fTreeS; fTreeS = 0;}
813
814  // Create the particle stack
815   if (fHeader) delete fHeader; 
816   fHeader = 0;
817   
818   // Get header from file
819   if(fTreeE) {
820       fTreeE->SetBranchAddress("Header", &fHeader);
821
822       if (!fTreeE->GetEntry(event)) {
823         Error("GetEvent","Cannot find event:%d\n",event);
824         return -1;
825       }
826   }  
827   else {
828       Error("GetEvent","Cannot find Header Tree (TE)\n");
829       return -1;
830   }
831
832   // Get the stack from the header, set fStack to 0 if it 
833   // fails to get event
834   if (fStack) delete fStack;
835   fStack = fHeader->Stack();
836   if (fStack) {
837     if (!fStack->GetEvent(event)) fStack = 0;
838   }
839
840   //
841   TFile *file = fTreeE->GetCurrentFile();
842   char treeName[20];
843   file->cd();
844
845   // Get Hits Tree header from file
846   sprintf(treeName,"TreeH%d",event);
847   fTreeH = (TTree*)gDirectory->Get(treeName);
848   if (!fTreeH) {
849     Error("GetEvent","cannot find Hits Tree for event:%d\n",event);
850   }
851   
852   // Get Digits Tree header from file
853   sprintf(treeName,"TreeD%d",event);
854   fTreeD = (TTree*)gDirectory->Get(treeName);
855   if (!fTreeD) {
856     // Warning("GetEvent","cannot find Digits Tree for event:%d\n",event);
857   }
858
859   file->cd();
860
861   // Get SDigits Tree header from file
862   sprintf(treeName,"TreeS%d",event);
863   fTreeS = (TTree*)gDirectory->Get(treeName);
864   if (!fTreeS) {
865     // Warning("GetEvent","cannot find SDigits Tree for event:%d\n",event);
866   }
867
868   file->cd();
869   
870   // Get Reconstruct Tree header from file
871   sprintf(treeName,"TreeR%d",event);
872   fTreeR = (TTree*)gDirectory->Get(treeName);
873   if (!fTreeR) {
874     //    printf("WARNING: cannot find Reconstructed Tree for event:%d\n",event);
875   }
876
877   file->cd();
878  
879   // Set Trees branch addresses
880   TIter next(fModules);
881   AliModule *detector;
882   while((detector = (AliModule*)next())) {
883     detector->SetTreeAddress();
884   }
885
886   return fStack->GetNtrack();
887 }
888
889 //_____________________________________________________________________________
890 TGeometry *AliRun::GetGeometry()
891 {
892   //
893   // Import Alice geometry from current file
894   // Return pointer to geometry object
895   //
896   if (!fGeometry) fGeometry = (TGeometry*)gDirectory->Get("AliceGeom");
897   //
898   // Unlink and relink nodes in detectors
899   // This is bad and there must be a better way...
900   //
901   
902   TIter next(fModules);
903   AliModule *detector;
904   while((detector = (AliModule*)next())) {
905     TList *dnodes=detector->Nodes();
906     Int_t j;
907     TNode *node, *node1;
908     for ( j=0; j<dnodes->GetSize(); j++) {
909       node = (TNode*) dnodes->At(j);
910       node1 = fGeometry->GetNode(node->GetName());
911       dnodes->Remove(node);
912       dnodes->AddAt(node1,j);
913     }
914   }
915   return fGeometry;
916 }
917
918 //_____________________________________________________________________________
919 void AliRun::GetNextTrack(Int_t &mtrack, Int_t &ipart, Float_t *pmom,
920                           Float_t &e, Float_t *vpos, Float_t *polar,
921                           Float_t &tof)
922 {
923   // Delegate to stack
924   //
925     fStack->GetNextTrack(mtrack, ipart, pmom, e, vpos, polar, tof);  
926 }
927
928 //_____________________________________________________________________________
929 Int_t AliRun::GetPrimary(Int_t track) const
930 {
931   //
932   // return number of primary that has generated track
933   //
934     return fStack->GetPrimary(track);
935 }
936  
937 //_____________________________________________________________________________
938 void AliRun::InitMC(const char *setup)
939 {
940   //
941   // Initialize the Alice setup
942   //
943
944   if(fInitDone) {
945     Warning("Init","Cannot initialise AliRun twice!\n");
946     return;
947   }
948     
949   gROOT->LoadMacro(setup);
950   gInterpreter->ProcessLine(fConfigFunction.Data());
951
952
953   gMC->DefineParticles();  //Create standard MC particles
954
955   TObject *objfirst, *objlast;
956
957   fNdets = fModules->GetLast()+1;
958
959   //
960   //=================Create Materials and geometry
961   gMC->Init();
962
963   // Added also after in case of interactive initialisation of modules
964   fNdets = fModules->GetLast()+1;
965
966    TIter next(fModules);
967    AliModule *detector;
968    while((detector = (AliModule*)next())) {
969       detector->SetTreeAddress();
970       objlast = gDirectory->GetList()->Last();
971       
972       // Add Detector histograms in Detector list of histograms
973       if (objlast) objfirst = gDirectory->GetList()->After(objlast);
974       else         objfirst = gDirectory->GetList()->First();
975       while (objfirst) {
976         detector->Histograms()->Add(objfirst);
977         objfirst = gDirectory->GetList()->After(objfirst);
978       }
979    }
980    ReadTransPar(); //Read the cuts for all materials
981    
982    MediaTable(); //Build the special IMEDIA table
983    
984    //Initialise geometry deposition table
985    fEventEnergy.Set(gMC->NofVolumes()+1);
986    fSummEnergy.Set(gMC->NofVolumes()+1);
987    fSum2Energy.Set(gMC->NofVolumes()+1);
988    
989    //Compute cross-sections
990    gMC->BuildPhysics();
991    
992    //Write Geometry object to current file.
993    fGeometry->Write();
994    
995    fInitDone = kTRUE;
996
997    fMCQA = new AliMCQA(fNdets);
998
999    AliConfig::Instance();
1000    //
1001    // Save stuff at the beginning of the file to avoid file corruption
1002    Write();
1003 }
1004
1005 //_____________________________________________________________________________
1006 void AliRun::MediaTable()
1007 {
1008   //
1009   // Built media table to get from the media number to
1010   // the detector id
1011   //
1012   Int_t kz, nz, idt, lz, i, k, ind;
1013   //  Int_t ibeg;
1014   TObjArray &dets = *gAlice->Detectors();
1015   AliModule *det;
1016   //
1017   // For all detectors
1018   for (kz=0;kz<fNdets;kz++) {
1019     // If detector is defined
1020     if((det=(AliModule*) dets[kz])) {
1021         TArrayI &idtmed = *(det->GetIdtmed()); 
1022         for(nz=0;nz<100;nz++) {
1023         // Find max and min material number
1024         if((idt=idtmed[nz])) {
1025           det->LoMedium() = det->LoMedium() < idt ? det->LoMedium() : idt;
1026           det->HiMedium() = det->HiMedium() > idt ? det->HiMedium() : idt;
1027         }
1028       }
1029       if(det->LoMedium() > det->HiMedium()) {
1030         det->LoMedium() = 0;
1031         det->HiMedium() = 0;
1032       } else {
1033         if(det->HiMedium() > fImedia->GetSize()) {
1034           Error("MediaTable","Increase fImedia from %d to %d",
1035                 fImedia->GetSize(),det->HiMedium());
1036           return;
1037         }
1038         // Tag all materials in rage as belonging to detector kz
1039         for(lz=det->LoMedium(); lz<= det->HiMedium(); lz++) {
1040           (*fImedia)[lz]=kz;
1041         }
1042       }
1043     }
1044   }
1045   //
1046   // Print summary table
1047   printf(" Traking media ranges:\n");
1048   for(i=0;i<(fNdets-1)/6+1;i++) {
1049     for(k=0;k< (6<fNdets-i*6?6:fNdets-i*6);k++) {
1050       ind=i*6+k;
1051       det=(AliModule*)dets[ind];
1052       if(det)
1053         printf(" %6s: %3d -> %3d;",det->GetName(),det->LoMedium(),
1054                det->HiMedium());
1055       else
1056         printf(" %6s: %3d -> %3d;","NULL",0,0);
1057     }
1058     printf("\n");
1059   }
1060 }
1061
1062 //____________________________________________________________________________
1063 void AliRun::SetGenerator(AliGenerator *generator)
1064 {
1065   //
1066   // Load the event generator
1067   //
1068   if(!fGenerator) fGenerator = generator;
1069 }
1070
1071 //____________________________________________________________________________
1072 void AliRun::ResetGenerator(AliGenerator *generator)
1073 {
1074   //
1075   // Load the event generator
1076   //
1077   if(fGenerator)
1078     if(generator)
1079       Warning("ResetGenerator","Replacing generator %s with %s\n",
1080               fGenerator->GetName(),generator->GetName());
1081     else
1082       Warning("ResetGenerator","Replacing generator %s with NULL\n",
1083               fGenerator->GetName());
1084   fGenerator = generator;
1085 }
1086
1087 //____________________________________________________________________________
1088 void AliRun::SetTransPar(char *filename)
1089 {
1090   fTransParName = filename;
1091 }
1092
1093 //____________________________________________________________________________
1094 void AliRun::SetBaseFile(char *filename)
1095 {
1096   fBaseFileName = filename;
1097 }
1098
1099 //____________________________________________________________________________
1100 void AliRun::ReadTransPar()
1101 {
1102   //
1103   // Read filename to set the transport parameters
1104   //
1105
1106
1107   const Int_t kncuts=10;
1108   const Int_t knflags=11;
1109   const Int_t knpars=kncuts+knflags;
1110   const char kpars[knpars][7] = {"CUTGAM" ,"CUTELE","CUTNEU","CUTHAD","CUTMUO",
1111                                "BCUTE","BCUTM","DCUTE","DCUTM","PPCUTM","ANNI",
1112                                "BREM","COMP","DCAY","DRAY","HADR","LOSS",
1113                                "MULS","PAIR","PHOT","RAYL"};
1114   char line[256];
1115   char detName[7];
1116   char* filtmp;
1117   Float_t cut[kncuts];
1118   Int_t flag[knflags];
1119   Int_t i, itmed, iret, ktmed, kz;
1120   FILE *lun;
1121   //
1122   // See whether the file is there
1123   filtmp=gSystem->ExpandPathName(fTransParName.Data());
1124   lun=fopen(filtmp,"r");
1125   delete [] filtmp;
1126   if(!lun) {
1127     Warning("ReadTransPar","File %s does not exist!\n",fTransParName.Data());
1128     return;
1129   }
1130   //
1131   if(fDebug) {
1132     printf(" "); for(i=0;i<60;i++) printf("*"); printf("\n");
1133     printf(" *%59s\n","*");
1134     printf(" *       Please check carefully what you are doing!%10s\n","*");
1135     printf(" *%59s\n","*");
1136   }
1137   //
1138   while(1) {
1139     // Initialise cuts and flags
1140     for(i=0;i<kncuts;i++) cut[i]=-99;
1141     for(i=0;i<knflags;i++) flag[i]=-99;
1142     itmed=0;
1143     for(i=0;i<256;i++) line[i]='\0';
1144     // Read up to the end of line excluded
1145     iret=fscanf(lun,"%[^\n]",line);
1146     if(iret<0) {
1147       //End of file
1148       fclose(lun);
1149       if(fDebug){
1150         printf(" *%59s\n","*");
1151         printf(" "); for(i=0;i<60;i++) printf("*"); printf("\n");
1152       }
1153       return;
1154     }
1155     // Read the end of line
1156     fscanf(lun,"%*c");
1157     if(!iret) continue;
1158     if(line[0]=='*') continue;
1159     // Read the numbers
1160     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",
1161                 detName,&itmed,&cut[0],&cut[1],&cut[2],&cut[3],&cut[4],&cut[5],&cut[6],&cut[7],&cut[8],
1162                 &cut[9],&flag[0],&flag[1],&flag[2],&flag[3],&flag[4],&flag[5],&flag[6],&flag[7],
1163                 &flag[8],&flag[9],&flag[10]);
1164     if(!iret) continue;
1165     if(iret<0) {
1166       //reading error
1167       Warning("ReadTransPar","Error reading file %s\n",fTransParName.Data());
1168       continue;
1169     }
1170     // Check that the module exist
1171     AliModule *mod = GetModule(detName);
1172     if(mod) {
1173       // Get the array of media numbers
1174       TArrayI &idtmed = *mod->GetIdtmed();
1175       // Check that the tracking medium code is valid
1176       if(0<=itmed && itmed < 100) {
1177         ktmed=idtmed[itmed];
1178         if(!ktmed) {
1179           Warning("ReadTransPar","Invalid tracking medium code %d for %s\n",itmed,mod->GetName());
1180           continue;
1181         }
1182         // Set energy thresholds
1183         for(kz=0;kz<kncuts;kz++) {
1184           if(cut[kz]>=0) {
1185             if(fDebug) printf(" *  %-6s set to %10.3E for tracking medium code %4d for %s\n",
1186                    kpars[kz],cut[kz],itmed,mod->GetName());
1187             gMC->Gstpar(ktmed,kpars[kz],cut[kz]);
1188           }
1189         }
1190         // Set transport mechanisms
1191         for(kz=0;kz<knflags;kz++) {
1192           if(flag[kz]>=0) {
1193             if(fDebug) printf(" *  %-6s set to %10d for tracking medium code %4d for %s\n",
1194                    kpars[kncuts+kz],flag[kz],itmed,mod->GetName());
1195             gMC->Gstpar(ktmed,kpars[kncuts+kz],Float_t(flag[kz]));
1196           }
1197         }
1198       } else {
1199         Warning("ReadTransPar","Invalid medium code %d *\n",itmed);
1200         continue;
1201       }
1202     } else {
1203       if(fDebug) printf("%s::ReadTransParModule: %s not present\n",ClassName(),detName);
1204       continue;
1205     }
1206   }
1207 }
1208
1209
1210 //_____________________________________________________________________________
1211 void AliRun::MakeTree(Option_t *option, const char *file)
1212 {
1213   //
1214   //  Create the ROOT trees
1215   //  Loop on all detectors to create the Root branch (if any)
1216   //
1217
1218   char hname[30];
1219   //
1220   // Analyse options
1221   const char *oK = strstr(option,"K");
1222   const char *oH = strstr(option,"H");
1223   const char *oE = strstr(option,"E");
1224   const char *oD = strstr(option,"D");
1225   const char *oR = strstr(option,"R");
1226   const char *oS = strstr(option,"S");
1227   //
1228
1229   TDirectory *cwd = gDirectory;
1230
1231   TBranch *branch = 0;
1232   
1233   if (oK) fStack->MakeTree(fEvent, file);
1234
1235   if (oE && !fTreeE) {
1236     fTreeE = new TTree("TE","Header");
1237     branch = fTreeE->Branch("Header", "AliHeader", &fHeader, 4000, 0);         
1238     branch->SetAutoDelete(kFALSE);           
1239     TFolder *folder = (TFolder *)gROOT->FindObjectAny("/Folders/RunMC/Event/Header");
1240     if (folder) folder->Add(fHeader);
1241 //    branch = fTreeE->Branch("Stack","AliStack", &fStack, 4000, 0);
1242 //    branch->SetAutoDelete(kFALSE);         
1243 //    if (folder) folder->Add(fStack);
1244     fTreeE->Write(0,TObject::kOverwrite);
1245   }
1246   
1247   if (file && branch) {
1248     char * outFile = new char[strlen(gAlice->GetBaseFile())+strlen(file)+2];
1249     sprintf(outFile,"%s/%s",GetBaseFile(),file);
1250     branch->SetFile(outFile);
1251     TIter next( branch->GetListOfBranches());
1252     while ((branch=(TBranch*)next())) {
1253        branch->SetFile(outFile);
1254     } 
1255     if (GetDebug()>1)
1256         printf("* MakeBranch * Diverting Branch %s to file %s\n", branch->GetName(),file);
1257     cwd->cd();
1258     delete outFile;
1259   }
1260   
1261   if (oH && !fTreeH) {
1262     sprintf(hname,"TreeH%d",fEvent);
1263     fTreeH = new TTree(hname,"Hits");
1264     fTreeH->SetAutoSave(1000000000); //no autosave
1265     fTreeH->Write(0,TObject::kOverwrite);
1266   }
1267   if (oD && !fTreeD) {
1268     sprintf(hname,"TreeD%d",fEvent);
1269     fTreeD = new TTree(hname,"Digits");
1270     fTreeD->Write(0,TObject::kOverwrite);
1271   }
1272   if (oS && !fTreeS) {
1273     sprintf(hname,"TreeS%d",fEvent);
1274     fTreeS = new TTree(hname,"SDigits");
1275     fTreeS->Write(0,TObject::kOverwrite);
1276   }
1277   if (oR && !fTreeR) {
1278     sprintf(hname,"TreeR%d",fEvent);
1279     fTreeR = new TTree(hname,"Reconstruction");
1280     fTreeR->Write(0,TObject::kOverwrite);
1281   }
1282
1283   //
1284   // Create a branch for hits/digits for each detector
1285   // Each branch is a TClonesArray. Each data member of the Hits classes
1286   // will be in turn a subbranch of the detector master branch
1287   TIter next(fModules);
1288   AliModule *detector;
1289   while((detector = (AliModule*)next())) {
1290      if (oH) detector->MakeBranch(option,file);
1291   }
1292 }
1293
1294 //_____________________________________________________________________________
1295 TParticle* AliRun::Particle(Int_t i)
1296 {
1297     return fStack->Particle(i);
1298 }
1299
1300 //_____________________________________________________________________________
1301 void AliRun::BeginEvent()
1302 {
1303     // Clean-up previous event
1304     // Energy scores  
1305     fEventEnergy.Reset();  
1306     // Clean detector information
1307     CleanDetectors();
1308     // Reset stack info
1309     fStack->Reset();
1310
1311  
1312   //
1313   //  Reset all Detectors & kinematics & trees
1314   //
1315   char hname[30];
1316   //
1317   // Initialise event header
1318   fHeader->Reset(fRun,fEvent);
1319   //
1320   fStack->BeginEvent(fEvent);
1321
1322   //
1323   if(fLego) {
1324     fLego->BeginEvent();
1325     return;
1326   }
1327
1328   //
1329
1330   ResetHits();
1331   ResetDigits();
1332   ResetSDigits();
1333
1334
1335   if(fTreeH) {
1336     fTreeH->Reset();
1337     sprintf(hname,"TreeH%d",fEvent);
1338     fTreeH->SetName(hname);
1339   }
1340   if(fTreeD) {
1341     fTreeD->Reset();
1342     sprintf(hname,"TreeD%d",fEvent);
1343     fTreeD->SetName(hname);
1344     fTreeD->Write(0,TObject::kOverwrite);
1345   }
1346   if(fTreeS) {
1347     fTreeS->Reset();
1348     sprintf(hname,"TreeS%d",fEvent);
1349     fTreeS->SetName(hname);
1350     fTreeS->Write(0,TObject::kOverwrite);
1351   }
1352   if(fTreeR) {
1353     fTreeR->Reset();
1354     sprintf(hname,"TreeR%d",fEvent);
1355     fTreeR->SetName(hname);
1356     fTreeR->Write(0,TObject::kOverwrite);
1357   }
1358 }
1359 //_____________________________________________________________________________
1360 void AliRun::ResetDigits()
1361 {
1362   //
1363   //  Reset all Detectors digits
1364   //
1365   TIter next(fModules);
1366   AliModule *detector;
1367   while((detector = (AliModule*)next())) {
1368      detector->ResetDigits();
1369   }
1370 }
1371
1372 //_____________________________________________________________________________
1373 void AliRun::ResetSDigits()
1374 {
1375   //
1376   //  Reset all Detectors digits
1377   //
1378   TIter next(fModules);
1379   AliModule *detector;
1380   while((detector = (AliModule*)next())) {
1381      detector->ResetSDigits();
1382   }
1383 }
1384
1385 //_____________________________________________________________________________
1386 void AliRun::ResetHits()
1387 {
1388   //
1389   //  Reset all Detectors hits
1390   //
1391   TIter next(fModules);
1392   AliModule *detector;
1393   while((detector = (AliModule*)next())) {
1394      detector->ResetHits();
1395   }
1396 }
1397
1398 //_____________________________________________________________________________
1399 void AliRun::ResetPoints()
1400 {
1401   //
1402   // Reset all Detectors points
1403   //
1404   TIter next(fModules);
1405   AliModule *detector;
1406   while((detector = (AliModule*)next())) {
1407      detector->ResetPoints();
1408   }
1409 }
1410
1411 //_____________________________________________________________________________
1412 void AliRun::RunMC(Int_t nevent, const char *setup)
1413 {
1414   //
1415   // Main function to be called to process a galice run
1416   // example
1417   //    Root > gAlice.Run(); 
1418   // a positive number of events will cause the finish routine
1419   // to be called
1420   //
1421
1422   // check if initialisation has been done
1423   if (!fInitDone) InitMC(setup);
1424   
1425   // Create the Root Tree with one branch per detector
1426
1427    MakeTree("ESDR");
1428
1429   if (gSystem->Getenv("CONFIG_SPLIT_FILE")) {
1430      MakeTree("K","Kine.root");
1431      MakeTree("H","Hits.root");
1432   } else {
1433      MakeTree("KH");
1434   }
1435
1436   gMC->ProcessRun(nevent);
1437
1438   // End of this run, close files
1439   if(nevent>0) FinishRun();
1440 }
1441
1442 //_____________________________________________________________________________
1443 void AliRun::RunReco(const char *selected, Int_t first, Int_t last)
1444 {
1445   //
1446   // Main function to be called to reconstruct Alice event
1447   // 
1448    cout << "Found "<< gAlice->TreeE()->GetEntries() << "events" << endl;
1449    Int_t nFirst = first;
1450    Int_t nLast  = (last < 0)? (Int_t) gAlice->TreeE()->GetEntries() : last;
1451    
1452    for (Int_t nevent = nFirst; nevent <= nLast; nevent++) {
1453      cout << "Processing event "<< nevent << endl;
1454      GetEvent(nevent);
1455      // MakeTree("R");
1456      Digits2Reco(selected);
1457    }
1458 }
1459
1460 //_____________________________________________________________________________
1461
1462 void AliRun::Hits2Digits(const char *selected)
1463 {
1464
1465    // Convert Hits to sumable digits
1466    // 
1467    for (Int_t nevent=0; nevent<gAlice->TreeE()->GetEntries(); nevent++) {
1468      GetEvent(nevent);
1469     // MakeTree("D");
1470      Hits2SDigits(selected);
1471      SDigits2Digits(selected);
1472    }  
1473 }
1474
1475
1476 //_____________________________________________________________________________
1477
1478 void AliRun::Tree2Tree(Option_t *option, const char *selected)
1479 {
1480   //
1481   // Function to transform the content of
1482   //  
1483   // - TreeH to TreeS (option "S")
1484   // - TreeS to TreeD (option "D")
1485   // - TreeD to TreeR (option "R")
1486   // 
1487   // If multiple options are specified ("SDR"), transformation will be done in sequence for
1488   // selected detector and for all detectors if none is selected (detector string 
1489   // can contain blank separated list of detector names). 
1490
1491
1492    const char *oS = strstr(option,"S");
1493    const char *oD = strstr(option,"D");
1494    const char *oR = strstr(option,"R");
1495    
1496    TObjArray *detectors = Detectors();
1497
1498    TIter next(detectors);
1499
1500    AliDetector *detector = 0;
1501
1502    TDirectory *cwd = gDirectory;
1503
1504    char outFile[32];
1505    
1506    while((detector = (AliDetector*)next())) {
1507      if (selected) 
1508        if (strcmp(detector->GetName(),selected)) continue;
1509      if (detector->IsActive()){ 
1510        if (gSystem->Getenv("CONFIG_SPLIT_FILE")) {          
1511           if (oS) {
1512             sprintf(outFile,"SDigits.%s.root",detector->GetName());
1513             detector->MakeBranch("S",outFile);
1514           }    
1515           if (oD) {
1516             sprintf(outFile,"Digits.%s.root",detector->GetName());
1517             detector->MakeBranch("D",outFile);
1518           }    
1519           if (oR) {
1520             sprintf(outFile,"Reco.%s.root",detector->GetName());
1521             detector->MakeBranch("R",outFile);
1522           }    
1523        } else {
1524           detector->MakeBranch(option);
1525        }
1526        
1527        cwd->cd(); 
1528
1529        if (oS) {
1530           cout << "Hits2SDigits: Processing " << detector->GetName() << "..." << endl;
1531           detector->Hits2SDigits(); 
1532        }  
1533        if (oD) {
1534           cout << "SDigits2Digits: Processing " << detector->GetName() << "..." << endl;
1535           detector->SDigits2Digits();
1536        } 
1537        if (oR) {
1538           cout << "Digits2Reco: Processing " << detector->GetName() << "..." << endl;
1539           detector->Digits2Reco(); 
1540        }
1541        
1542        cwd->cd();        
1543      }   
1544    }
1545 }
1546
1547
1548 //_____________________________________________________________________________
1549 void AliRun::RunLego(const char *setup, Int_t nc1, Float_t c1min,
1550                      Float_t c1max,Int_t nc2,Float_t c2min,Float_t c2max,
1551                      Float_t rmin,Float_t rmax,Float_t zmax, AliLegoGenerator* gener)
1552 {
1553   //
1554   // Generates lego plots of:
1555   //    - radiation length map phi vs theta
1556   //    - radiation length map phi vs eta
1557   //    - interaction length map
1558   //    - g/cm2 length map
1559   //
1560   //  ntheta    bins in theta, eta
1561   //  themin    minimum angle in theta (degrees)
1562   //  themax    maximum angle in theta (degrees)
1563   //  nphi      bins in phi
1564   //  phimin    minimum angle in phi (degrees)
1565   //  phimax    maximum angle in phi (degrees)
1566   //  rmin      minimum radius
1567   //  rmax      maximum radius
1568   //  
1569   //
1570   //  The number of events generated = ntheta*nphi
1571   //  run input parameters in macro setup (default="Config.C")
1572   //
1573   //  Use macro "lego.C" to visualize the 3 lego plots in spherical coordinates
1574   //Begin_Html
1575   /*
1576     <img src="picts/AliRunLego1.gif">
1577   */
1578   //End_Html
1579   //Begin_Html
1580   /*
1581     <img src="picts/AliRunLego2.gif">
1582   */
1583   //End_Html
1584   //Begin_Html
1585   /*
1586     <img src="picts/AliRunLego3.gif">
1587   */
1588   //End_Html
1589   //
1590
1591   // check if initialisation has been done
1592   if (!fInitDone) InitMC(setup);
1593   //Save current generator
1594   AliGenerator *gen=Generator();
1595
1596   // Set new generator
1597   if (!gener) gener  = new AliLegoGenerator();
1598   ResetGenerator(gener);
1599   //
1600   // Configure Generator
1601   gener->SetRadiusRange(rmin, rmax);
1602   gener->SetZMax(zmax);
1603   gener->SetCoor1Range(nc1, c1min, c1max);
1604   gener->SetCoor2Range(nc2, c2min, c2max);
1605   
1606   
1607   //Create Lego object  
1608   fLego = new AliLego("lego",gener);
1609
1610   //Prepare MC for Lego Run
1611   gMC->InitLego();
1612   
1613   //Run Lego Object
1614
1615   gMC->ProcessRun(nc1*nc2+1);
1616   
1617   // Create only the Root event Tree
1618   MakeTree("E");
1619   
1620   // End of this run, close files
1621   FinishRun();
1622   // Restore current generator
1623   ResetGenerator(gen);
1624   // Delete Lego Object
1625   delete fLego; fLego=0;
1626 }
1627
1628 //_____________________________________________________________________________
1629 void AliRun::SetConfigFunction(const char * config) 
1630 {
1631   //
1632   // Set the signature of the function contained in Config.C to configure
1633   // the run
1634   //
1635   fConfigFunction=config;
1636 }
1637
1638 //_____________________________________________________________________________
1639 void AliRun::SetCurrentTrack(Int_t track)
1640
1641   //
1642   // Set current track number
1643   //
1644     fStack->SetCurrentTrack(track); 
1645 }
1646  
1647 //_____________________________________________________________________________
1648 void AliRun::SetTrack(Int_t done, Int_t parent, Int_t pdg, Float_t *pmom,
1649                       Float_t *vpos, Float_t *polar, Float_t tof,
1650                       AliMCProcess mech, Int_t &ntr, Float_t weight)
1651
1652 // Delegate to stack
1653 //
1654     fStack->SetTrack(done, parent, pdg, pmom, vpos, polar, tof,
1655                      mech, ntr, weight);
1656 }
1657
1658 //_____________________________________________________________________________
1659 void AliRun::SetTrack(Int_t done, Int_t parent, Int_t pdg,
1660                       Double_t px, Double_t py, Double_t pz, Double_t e,
1661                       Double_t vx, Double_t vy, Double_t vz, Double_t tof,
1662                       Double_t polx, Double_t poly, Double_t polz,
1663                       AliMCProcess mech, Int_t &ntr, Float_t weight)
1664
1665   // Delegate to stack
1666   //
1667     fStack->SetTrack(done, parent, pdg, px, py, pz, e, vx, vy, vz, tof,
1668                    polx, poly, polz, mech, ntr, weight);
1669     
1670 }
1671
1672 //_____________________________________________________________________________
1673 void AliRun::SetHighWaterMark(const Int_t nt)
1674 {
1675     //
1676     // Set high water mark for last track in event
1677     fStack->SetHighWaterMark(nt);
1678 }
1679
1680 //_____________________________________________________________________________
1681 void AliRun::KeepTrack(const Int_t track)
1682
1683   //
1684   // Delegate to stack
1685   //
1686     fStack->KeepTrack(track);
1687 }
1688  
1689 //_____________________________________________________________________________
1690 void AliRun::StepManager(Int_t id) 
1691 {
1692   //
1693   // Called at every step during transport
1694   //
1695
1696   //
1697   // --- If lego option, do it and leave 
1698   if (fLego)
1699     fLego->StepManager();
1700   else {
1701     Int_t copy;
1702     //Update energy deposition tables
1703     AddEnergyDeposit(gMC->CurrentVolID(copy),gMC->Edep());
1704   
1705     //Call the appropriate stepping routine;
1706     AliModule *det = (AliModule*)fModules->At(id);
1707     if(det) {
1708       fMCQA->StepManager(id);
1709       det->StepManager();
1710     }
1711   }
1712 }
1713
1714 //_____________________________________________________________________________
1715 void AliRun::Streamer(TBuffer &R__b)
1716 {
1717    // Stream an object of class AliRun.
1718
1719    if (R__b.IsReading()) {
1720       if (!gAlice) gAlice = this;
1721
1722       AliRun::Class()->ReadBuffer(R__b, this);
1723       //
1724       gROOT->GetListOfBrowsables()->Add(this,"Run");
1725
1726       fTreeE = (TTree*)gDirectory->Get("TE");
1727       if (fTreeE) {
1728           fTreeE->SetBranchAddress("Header", &fHeader);
1729       }
1730       
1731       else    Error("Streamer","cannot find Header Tree\n");
1732       fTreeE->GetEntry(0);
1733
1734       gRandom = fRandom;
1735    } else {
1736       AliRun::Class()->WriteBuffer(R__b, this);
1737    }
1738 }
1739
1740
1741 //___________________________________________________________________________
1742 Int_t AliRun::CurrentTrack() const {
1743   //
1744   // Returns current track
1745   //
1746   return fStack->CurrentTrack();
1747 }
1748
1749 //___________________________________________________________________________
1750 Int_t AliRun::GetNtrack() const {
1751   //
1752   // Returns number of tracks in stack
1753   //
1754   return fStack->GetNtrack();
1755 }
1756
1757 //___________________________________________________________________________
1758 TObjArray* AliRun::Particles() {
1759   //
1760   // Returns pointer to Particles array
1761   //
1762   return fStack->Particles();
1763 }
1764
1765 //___________________________________________________________________________
1766 TTree* AliRun::TreeK() {
1767   //
1768   // Returns pointer to the TreeK array
1769   //
1770   return fStack->TreeK();
1771 }
1772
1773
1774 void AliRun::SetGenEventHeader(AliGenEventHeader* header)
1775 {
1776     fHeader->SetGenEventHeader(header);
1777 }