]> git.uio.no Git - u/mrichter/AliRoot.git/blob - STEER/AliRunLoader.cxx
changed the names of the histograms, requested by AMORE
[u/mrichter/AliRoot.git] / STEER / AliRunLoader.cxx
1 /**************************************************************************
2  * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
3  *                                                                        *
4  * Author: The ALICE Off-line Project.                                    *
5  * Contributors are mentioned in the code where appropriate.              *
6  *                                                                        *
7  * Permission to use, copy, modify and distribute this software and its   *
8  * documentation strictly for non-commercial purposes is hereby granted   *
9  * without fee, provided that the above copyright notice appears in all   *
10  * copies and that both the copyright notice and this permission notice   *
11  * appear in the supporting documentation. The authors make no claims     *
12  * about the suitability of this software for any purpose. It is          *
13  * provided "as is" without express or implied warranty.                  *
14  **************************************************************************/
15
16 /* $Id$ */
17
18 //____________________________________________________________________
19 //////////////////////////////////////////////////////////////////////
20 //                                                                  //
21 // class AliRunLoader                                               //
22 //                                                                  //
23 // This class aims to be the unque interface for managing data I/O. //
24 // It stores Loaders for all modules which, knows names             //
25 // of the files were data are to be stored.                         //
26 //                                                                  //
27 // It aims to substitud AliRun in automatic data managing           //
28 // thus there is no necessity of loading gAlice from file in order  //
29 // to get access to the data.                                       //
30 //                                                                  //
31 // Logical place to put the specific Loader to the given            //
32 // detector is detector  itself (i.e ITSLoader in ITS).             //
33 // But, to load detector object one need to load gAlice, and        //
34 // by the way all other detectors with their geometrieces and       //
35 // so on. So, if one need to open TPC clusters there is no          //
36 // principal need to read everything.                               //
37 //                                                                  //
38 //                                                                  //
39 // When RunLoader is read from the file it does not connect to      //
40 // the folder structure automatically. It must be connected         //
41 // (mounted) manualy. Default event folder is defined by            //
42 // AliConfig::GetDefaultEventFolderName()                           //
43 // but can be mounted elsewhere. Usefull specially in merging case, //
44 // when more than pone session needs to be loaded                   //
45 //                                                                  //
46 //////////////////////////////////////////////////////////////////////
47
48 #include <TROOT.h>
49 #include <TBranch.h>
50 #include <TFile.h>
51 #include <TFolder.h>
52 #include <TObjArray.h>
53 #include <TString.h>
54 class TTask;
55 #include <TTree.h>
56
57 #include "AliLog.h"
58 #include "AliRun.h"
59 #include "AliConfig.h"
60 #include "AliLoader.h"
61 #include "AliHeader.h"
62 #include "AliStack.h"
63 #include "AliDetector.h"
64 #include "AliCDBManager.h"
65 #include "AliCDBLocal.h"
66 #include "AliCentralTrigger.h"
67
68 ClassImp(AliRunLoader)
69
70 AliRunLoader* AliRunLoader::fgRunLoader = 0x0;
71
72 const TString AliRunLoader::fgkRunLoaderName("RunLoader");
73 const TString AliRunLoader::fgkHeaderBranchName("Header");
74 const TString AliRunLoader::fgkTriggerBranchName("ClassMask");
75 const TString AliRunLoader::fgkHeaderContainerName("TE");
76 const TString AliRunLoader::fgkTriggerContainerName("TreeCT");
77 const TString AliRunLoader::fgkKineContainerName("TreeK");
78 const TString AliRunLoader::fgkTrackRefsContainerName("TreeTR");
79 const TString AliRunLoader::fgkKineBranchName("Particles");
80 const TString AliRunLoader::fgkDefaultKineFileName("Kinematics.root");
81 const TString AliRunLoader::fgkDefaultTrackRefsFileName("TrackRefs.root");
82 const TString AliRunLoader::fgkGAliceName("gAlice");
83 const TString AliRunLoader::fgkDefaultTriggerFileName("Trigger.root");
84 /**************************************************************************/
85
86 AliRunLoader::AliRunLoader():
87  fLoaders(0x0),
88  fEventFolder(0x0),
89  fRun(-1),
90  fCurrentEvent(0),
91  fGAFile(0x0),
92  fHeader(0x0),
93  fStack(0x0),
94  fCTrigger(0x0),
95  fKineDataLoader(0x0),
96  fTrackRefsDataLoader(0x0),
97  fNEventsPerFile(1),
98  fNEventsPerRun(0),
99  fUnixDirName(".")
100 {
101   AliConfig::Instance();//force to build the folder structure
102   if (!fgRunLoader) fgRunLoader = this;
103 }
104 /**************************************************************************/
105
106 AliRunLoader::AliRunLoader(const char* eventfoldername):
107  TNamed(fgkRunLoaderName,fgkRunLoaderName),
108  fLoaders(new TObjArray()),
109  fEventFolder(0x0),
110  fRun(-1),
111  fCurrentEvent(0),
112  fGAFile(0x0),
113  fHeader(0x0),
114  fStack(0x0),
115  fCTrigger(0x0),
116  fKineDataLoader(new AliDataLoader(fgkDefaultKineFileName,fgkKineContainerName,"Kinematics")),
117  fTrackRefsDataLoader(new AliDataLoader(fgkDefaultTrackRefsFileName,fgkTrackRefsContainerName,"Track References")),
118  fNEventsPerFile(1),
119  fNEventsPerRun(0),
120  fUnixDirName(".")
121 {
122 //ctor
123   SetEventFolderName(eventfoldername);
124  if (!fgRunLoader) fgRunLoader = this;
125 }
126 /**************************************************************************/
127
128 AliRunLoader::~AliRunLoader()
129 {
130 //dtor
131   if (fgRunLoader == this) fgRunLoader = 0x0;
132   
133   UnloadHeader();
134   UnloadgAlice();
135   
136   if(fLoaders) {
137     fLoaders->SetOwner();
138     delete fLoaders;
139   }
140   
141   delete fKineDataLoader;
142   delete fTrackRefsDataLoader;
143   
144   
145   RemoveEventFolder();
146   
147   //fEventFolder is deleted by the way of removing - TopAliceFolder owns it
148   if( fCTrigger ) delete  fCTrigger;
149   delete fHeader;
150   delete fStack;
151   delete fGAFile;
152 }
153 /**************************************************************************/
154
155 AliRunLoader::AliRunLoader(TFolder* topfolder):
156  TNamed(fgkRunLoaderName,fgkRunLoaderName),
157  fLoaders(new TObjArray()),
158  fEventFolder(topfolder),
159  fRun(-1),
160  fCurrentEvent(0),
161  fGAFile(0x0),
162  fHeader(0x0),
163  fStack(0x0),
164  fCTrigger(0x0),
165  fKineDataLoader(new AliDataLoader(fgkDefaultKineFileName,fgkKineContainerName,"Kinematics")),
166  fTrackRefsDataLoader(new AliDataLoader(fgkDefaultTrackRefsFileName,fgkTrackRefsContainerName,"Track References")),
167  fNEventsPerFile(1),
168  fNEventsPerRun(0),
169  fUnixDirName(".")
170 {
171 //ctor
172  if(topfolder == 0x0)
173   {
174     TString errmsg("Parameter is NULL");
175     AliError(errmsg.Data());
176     throw errmsg;
177     return;
178   }
179  
180  TObject* obj = fEventFolder->FindObject(fgkRunLoaderName);
181  if (obj)
182   { //if it is, then sth. is going wrong... exits aliroot session
183     TString errmsg("In Event Folder Named ");
184     errmsg+=fEventFolder->GetName();
185     errmsg+=" object named "+fgkRunLoaderName+" already exists. I am confused ...";
186
187     AliError(errmsg.Data());
188     throw errmsg;
189     return;//never reached
190   }
191
192  if (!fgRunLoader) fgRunLoader = this;
193    
194  fEventFolder->Add(this);//put myself to the folder to accessible for all
195   
196 }
197
198 /**************************************************************************/
199
200 Int_t AliRunLoader::GetEvent(Int_t evno)
201 {
202 //Gets event number evno
203 //Reloads all data properly
204 //PH  if (fCurrentEvent == evno) return 0;
205   
206   if (evno < 0)
207    {
208      AliError("Can not give the event with negative number");
209      return 4;
210    }
211
212   if (evno >= GetNumberOfEvents())
213    {
214      AliError(Form("There is no event with number %d",evno));
215      return 3;
216    }
217   
218   AliDebug(1, ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
219   AliDebug(1, ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
220   AliDebug(1, ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
221   AliDebug(1, Form("          GETTING EVENT  %d",evno));
222   AliDebug(1, ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
223   AliDebug(1, ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
224   AliDebug(1, ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
225    
226   fCurrentEvent = evno;
227
228   Int_t retval;
229   
230   //Reload header (If header was loaded)
231   if (GetHeader())
232    {
233      retval = TreeE()->GetEvent(fCurrentEvent);
234      if ( retval == 0)
235       {
236         AliError(Form("Cannot find event: %d\n ",fCurrentEvent));
237         return 5;
238       }
239    }
240   //Reload stack (If header was loaded)
241   if (TreeE()) fStack = GetHeader()->Stack();
242   //Set event folder in stack (it does not mean that we read kinematics from file)
243    if( GetTrigger() && TreeCT() ) {
244       retval = TreeCT()->GetEvent(fCurrentEvent);
245       if ( retval < 0 )      {
246          AliError(Form("Error occured while GetEvent for Trigger. Event %d",evno));
247          return 2;
248       }
249    }
250   
251   retval = SetEvent();
252   if (retval)
253    {
254      AliError(Form("Error occured while setting event %d",evno));
255      return 1;
256    }
257    
258   //Post Track References
259   retval = fTrackRefsDataLoader->GetEvent();
260   if (retval)
261    {
262      AliError(Form("Error occured while GetEvent for Track References. Event %d",evno));
263      return 2;
264    }
265
266   //Read Kinematics if loaded
267   retval = fKineDataLoader->GetEvent();
268   if (retval)
269    {
270      AliError(Form("Error occured while GetEvent for Kinematics. Event %d",evno));
271      return 2;
272    }
273
274   if (fStack && fKineDataLoader->GetBaseLoader(0)->IsLoaded())
275     {
276         fStack->ConnectTree(TreeK());
277         
278       if (fStack->GetEvent() == kFALSE)
279         {
280           AliError(Form("Error occured while GetEvent for Stack. Event %d",evno));
281           return 2;
282         }
283     }
284
285   //Trigger data reloading in all loaders 
286   TIter next(fLoaders);
287   AliLoader *loader;
288   while((loader = (AliLoader*)next())) 
289    {
290      retval = loader->GetEvent();
291      if (retval)
292       {
293        AliError(Form("Error occured while getting event for %s. Event %d.",
294                      loader->GetDetectorName().Data(), evno));
295        return 3;
296       }
297    }
298   
299   SetDetectorAddresses();
300   
301   return 0;
302 }
303 /**************************************************************************/
304 Int_t AliRunLoader::SetEvent()
305 {
306 //if kinematics was loaded Cleans folder data
307
308   Int_t retval;
309   
310   retval = fKineDataLoader->SetEvent();
311   if (retval)
312    {
313      AliError("SetEvent for Kinamtics Data Loader retutned error.");
314      return retval;
315    }
316   retval = fTrackRefsDataLoader->SetEvent(); 
317   if (retval)
318    {
319      AliError("SetEvent for Track References Data Loader retutned error.");
320      return retval;
321    }
322
323   TIter next(fLoaders);
324   AliLoader *loader;
325   while((loader = (AliLoader*)next())) 
326    {
327      retval = loader->SetEvent();
328      if (retval)
329       {
330         AliError(Form("SetEvent for %s Data Loader retutned error.",loader->GetName()));
331         return retval;
332       }
333    }
334
335   return 0;
336 }
337 /**************************************************************************/
338
339 Int_t AliRunLoader::SetEventNumber(Int_t evno)
340 {
341   //cleans folders and sets the root dirs in files 
342   if (fCurrentEvent == evno) return 0;
343   fCurrentEvent = evno;
344   return SetEvent();
345 }
346
347 /**************************************************************************/
348 AliCDBEntry* AliRunLoader::GetCDBEntry(const char* name) const
349 {
350 //Get an AliCDBEntry from the run data storage
351
352   if ( !(AliCDBManager::Instance()->IsDefaultStorageSet()) ) {
353     AliError("No run data storage defined!");
354     return 0x0;
355   }
356   return AliCDBManager::Instance()->GetDefaultStorage()->Get(name, GetHeader()->GetRun());
357
358 }
359
360 /**************************************************************************/
361 AliRunLoader* AliRunLoader::Open
362   (const char* filename, const char* eventfoldername, Option_t* option)
363 {
364 //Opens a desired file 'filename'
365 //gets the the run-Loader and mounts it desired folder
366 //returns the pointer to run Loader which can be further used for accessing data 
367 //in case of error returns NULL
368  
369  static const TString kwebaddress("http://alisoft.cern.ch/people/skowron/codedoc/split/index.html");
370  AliDebugClass(1,Form("\n\n\nNew I/O strcture: See more info:\n %s\n\n\n",kwebaddress.Data()));
371  
372  AliRunLoader* result = 0x0;
373  
374  /* ************************************************ */
375  /* Chceck if folder with given name already exists  */
376  /* ************************************************ */
377  
378  TObject* obj = AliConfig::Instance()->GetTopFolder()->FindObject(eventfoldername);
379  if(obj)
380   {
381     TFolder* fold = dynamic_cast<TFolder*>(obj);
382     if (fold == 0x0)
383      {
384       AliErrorClass("Such a obejct already exists in top alice folder and it is not a folder.");
385       return 0x0;
386      }
387     
388     //check if we can get RL from that folder
389     result = AliRunLoader::GetRunLoader(eventfoldername);
390     if (result == 0x0)
391      {
392        AliErrorClass(Form("Folder %s already exists, and can not find session there. Can not mount.",eventfoldername));
393        return 0x0;
394      }
395
396     if (result->GetFileName().CompareTo(filename) != 0)
397      {
398        AliErrorClass("Other file is mounted in demanded folder. Can not mount.");
399        return 0x0;
400      }
401
402     //check if now is demanded (re)creation 
403     if ( AliLoader::TestFileOption(option) == kFALSE)
404      {
405        AliErrorClass(Form("Session already exists in folder %s and this session option is %s. Unable to proceed.",
406                           eventfoldername,option));
407        return 0x0;
408      }
409      
410     //check if demanded option is update and existing one 
411     TString tmpstr(option);
412     if ( (tmpstr.CompareTo("update",TString::kIgnoreCase) == 0) && 
413          (result->fGAFile->IsWritable() == kFALSE) )
414      { 
415        AliErrorClass(Form("Session already exists in folder %s and is not writable while this session option is %s. Unable to proceed.",
416                           eventfoldername,option));
417        return 0x0;
418      }
419      
420     AliWarningClass("Session is already opened and mounted in demanded folder");        
421     if (!fgRunLoader) fgRunLoader = result; //PH get access from any place
422     return result;
423   } //end of checking in case of existance of object named identically that folder session is being opened
424  
425  
426  TFile * gAliceFile = TFile::Open(filename,option);//open a file
427  if (!gAliceFile) 
428   {//null pointer returned
429     AliFatalClass(Form("Can not open file %s.",filename));
430     return 0x0;
431   }
432   
433  if (gAliceFile->IsOpen() == kFALSE)
434   {//pointer to valid object returned but file is not opened
435     AliErrorClass(Form("Can not open file %s.",filename));
436     return 0x0;
437   }
438  
439  //if file is "read" or "update" than we try to find AliRunLoader there - if not found cry and exit
440  //else create new AliRunLoader
441  if ( AliLoader::TestFileOption(option) )
442   { 
443     AliDebugClass(1, "Reading RL from file");
444     
445     result = dynamic_cast<AliRunLoader*>(gAliceFile->Get(fgkRunLoaderName));//get the run Loader from the file
446     if (result == 0x0)
447      {//didn't get
448        AliErrorClass(Form("Can not find run-Loader in file %s.",filename));
449        delete gAliceFile;//close the file
450        return 0x0;
451      }
452     Int_t tmp = result->SetEventFolderName(eventfoldername);//mount a event folder   
453     if (tmp)//if SetEvent  returned error
454      {
455        AliErrorClass(Form("Can not mount event in folder %s.",eventfoldername));
456        delete result; //delete run-Loader
457        delete gAliceFile;//close the file
458        return 0x0;
459      }
460   }
461  else
462   {
463     AliDebugClass(1, Form("Creating new AliRunLoader. Folder name is %s",eventfoldername));
464     try
465      {  
466        result = new AliRunLoader(eventfoldername);
467      }
468     catch (TString& errmsg)
469      {
470        AliErrorClass(Form("AliRunLoader constrcutor has thrown exception: %s\n",errmsg.Data()));
471        delete result;
472        delete gAliceFile;//close the file
473        return 0x0;
474      }
475   }
476  
477 //procedure for extracting dir name from the file name 
478  TString fname(filename);
479  Int_t  nsl = fname.Last('#');//look for hash in file name
480  TString dirname;
481  if (nsl < 0) {//hash not found
482    nsl = fname.Last('/');// look for slash
483    if (nsl < 0) 
484      nsl = fname.Last(':');// look for colon e.g. rfio:galice.root
485  }
486
487  if (nsl < 0) dirname = "./";      // no directory path, use "."
488  else dirname = fname.Remove(nsl+1);// directory path
489  
490  AliDebugClass(1, Form("Dir name is : %s",dirname.Data()));
491  
492  result->SetDirName(dirname); 
493  result->SetGAliceFile(gAliceFile);//set the pointer to gAliceFile
494  if (!fgRunLoader) fgRunLoader = result; //PH get access from any place
495  return result;
496 }
497 /**************************************************************************/
498 Int_t AliRunLoader::GetNumberOfEvents()
499 {
500  //returns number of events in Run
501  Int_t retval;
502  if( TreeE() == 0x0 )
503   {
504     retval = LoadHeader();
505     if (retval) 
506      {
507        AliError("Error occured while loading header");
508        return -1;
509      }
510   }
511  return (Int_t)TreeE()->GetEntries();
512 }
513 /**************************************************************************/
514
515 void AliRunLoader::MakeHeader()
516 {
517  //Makes header and connects it to header tree (if it exists)
518   AliDebug(1, "");
519   if(fHeader == 0x0)
520    {
521      AliDebug(1, "Creating new Header Object");
522      fHeader= new AliHeader();
523    }
524   TTree* tree = TreeE();
525   if (tree)
526    {
527      AliDebug(1, "Got Tree from folder.");
528      TBranch* branch = tree->GetBranch(fgkHeaderBranchName);
529      if (branch == 0x0)
530       {
531         AliDebug(1, "Creating new branch");
532         branch = tree->Branch(fgkHeaderBranchName, "AliHeader", &fHeader, 4000, 0);
533         branch->SetAutoDelete(kFALSE);
534       }
535      else
536       {
537         AliDebug(1, "Got Branch from Tree");
538         branch->SetAddress(&fHeader);
539         tree->GetEvent(fCurrentEvent);
540         fStack = fHeader->Stack(); //should be safe - if we created Stack, header returns pointer to the same object
541         if (fStack)
542          {
543            if (TreeK()) {
544                fStack->ConnectTree(TreeK());
545                fStack->GetEvent();
546            }
547          }
548         else
549         {
550           AliDebug(1, "Header does not have a stack.");
551         }
552       }
553    } 
554   AliDebug(1, "Exiting MakeHeader method");
555 }
556 /**************************************************************************/
557
558 void AliRunLoader::MakeStack()
559 {
560 //Creates the stack object -  do not connect the tree
561   if(fStack == 0x0)
562    { 
563      fStack = new AliStack(10000);
564    }
565 }
566 /**************************************************************************/
567
568 void AliRunLoader::MakeTrigger()
569 {
570  // Makes trigger object and connects it to trigger tree (if it exists)
571    AliDebug( 1, "" );
572    if( fCTrigger == 0x0 ) {
573       AliDebug( 1, "Creating new Trigger Object" );
574       fCTrigger = new AliCentralTrigger();
575    }
576    TTree* tree = TreeCT();
577    if( tree ) {
578       fCTrigger->MakeBranch( fgkTriggerBranchName, tree );
579       tree->GetEvent( fCurrentEvent );
580    }
581
582    AliDebug( 1, "Exiting MakeTrigger method" );
583 }
584 /**************************************************************************/
585
586 void AliRunLoader::MakeTree(Option_t *option)
587 {
588 //Creates trees
589   const char *oK  = strstr(option,"K");  //Kine
590   const char *oE  = strstr(option,"E");  //Header
591   const char *oGG = strstr(option,"GG"); //Central TriGGer
592   
593   if(oK)
594   { 
595       if (fKineDataLoader->GetBaseLoader(0)->IsLoaded() == kFALSE)
596       {
597           AliError("Load Kinematics first");
598       }
599       else
600       {
601           if (!TreeK()) {
602               fKineDataLoader->MakeTree();
603               MakeStack();
604           } 
605           fStack->ConnectTree(TreeK());
606           WriteKinematics("OVERWRITE");
607       }
608   } // TreeK
609   
610   if(oE && !TreeE())
611    { 
612      fGAFile->cd();
613      TTree* tree = new TTree(fgkHeaderContainerName,"Tree with Headers");
614      GetEventFolder()->Add(tree);
615      MakeHeader();
616      WriteHeader("OVERWRITE");
617    }
618   
619    if(oGG && !TreeCT())
620    {
621       // create the CTP Trigger output file and tree
622       TFile* file = gROOT->GetFile( fgkDefaultTriggerFileName );
623       if( !file ) {
624          file = TFile::Open( gSystem->ConcatFileName( fUnixDirName.Data(), fgkDefaultTriggerFileName.Data() ), "RECREATE" ) ;
625       }
626
627       file->cd();
628       TTree* tree = new TTree( fgkTriggerContainerName, "Tree with Central Trigger Mask" );
629       GetEventFolder()->Add(tree);
630       MakeTrigger();
631   //    WriteHeader("OVERWRITE");
632    }
633
634   TIter next(fLoaders);
635   AliLoader *loader;
636   while((loader = (AliLoader*)next()))
637    {
638     loader->MakeTree(option);
639    }
640
641 }
642 /**************************************************************************/
643     
644 Int_t AliRunLoader::LoadgAlice()
645 {
646 //Loads gAlice from file
647  if (GetAliRun())
648   {
649     AliWarning("AliRun is already in folder. Unload first.");
650     return 0;
651   }
652  AliRun* alirun = dynamic_cast<AliRun*>(fGAFile->Get(fgkGAliceName));
653  if (alirun == 0x0)
654   {
655     AliError(Form("Can not find gAlice in file %s",fGAFile->GetName()));
656     return 2;
657   }
658  alirun->SetRunLoader(this);
659  if (gAlice)
660   {
661     AliWarning(Form("gAlice already exists. Putting retrived object in folder named %s",
662                     GetEventFolder()->GetName()));
663   }
664  else
665   {
666     gAlice = alirun;
667   }
668  SetDetectorAddresses();//calls SetTreeAddress for all detectors
669  return 0; 
670 }
671 /**************************************************************************/
672
673 Int_t AliRunLoader::LoadHeader()
674 {
675 //loads treeE and reads header object for current event
676  if (TreeE())
677   {
678      AliWarning("Header is already loaded. Use ReloadHeader to force reload. Nothing done");
679      return 0;
680   }
681  
682  if (GetEventFolder() == 0x0)
683   {
684     AliError("Event folder not specified yet");
685     return 1;
686   }
687
688  if (fGAFile == 0x0)
689   {
690     AliError("Session not opened. Use AliRunLoader::Open");
691     return 2;
692   }
693  
694  if (fGAFile->IsOpen() == kFALSE)
695   {
696     AliError("Session not opened. Use AliRunLoader::Open");
697     return 2;
698   }
699
700  TTree* tree = dynamic_cast<TTree*>(fGAFile->Get(fgkHeaderContainerName));
701  if (tree == 0x0)
702   {
703     AliError(Form("Can not find header tree named %s in file %s",
704                   fgkHeaderContainerName.Data(),fGAFile->GetName()));
705     return 2;
706   }
707
708  if (tree == TreeE()) return 0;
709
710  CleanHeader();
711  GetEventFolder()->Add(tree);
712  MakeHeader();//creates header object and connects to tree
713  return 0; 
714
715 }
716 /**************************************************************************/
717
718 Int_t AliRunLoader::LoadTrigger(Option_t* option)
719 {
720    //Load treeCT
721
722    if( TreeCT() ) {
723       AliWarning("Trigger is already loaded. Nothing done");
724       return 0;
725    }
726  
727    if( GetEventFolder() == 0x0 ) {
728       AliError("Event folder not specified yet");
729       return 1;
730    }
731    // get the CTP Trigger output file and tree
732    TString trgfile = gSystem->ConcatFileName( fUnixDirName.Data(),
733                                               fgkDefaultTriggerFileName.Data() );
734    TFile* file = gROOT->GetFile( trgfile );
735    if( !file ) {
736       file = TFile::Open( trgfile, option ) ;
737       if (!file || file->IsOpen() == kFALSE ) {
738          AliError( Form( "Can not open trigger file %s", trgfile.Data() ) );
739          return 2;
740       }
741    }
742    file->cd();
743
744    TTree* tree = dynamic_cast<TTree*>(file->Get( fgkTriggerContainerName ));
745    if( !tree ) {
746       AliError( Form( "Can not find trigger tree named %s in file %s",
747                       fgkTriggerContainerName.Data(), file->GetName() ) );
748       return 2;
749    }
750
751    CleanTrigger();
752
753    fCTrigger = dynamic_cast<AliCentralTrigger*>(file->Get( "AliCentralTrigger" ));
754    GetEventFolder()->Add( tree );
755    MakeTrigger();
756
757    return 0;
758 }
759
760 /**************************************************************************/
761
762 Int_t AliRunLoader::LoadKinematics(Option_t* option)
763 {
764 //Loads the kinematics 
765  Int_t retval = fKineDataLoader->GetBaseLoader(0)->Load(option);
766  if (retval)
767   {
768     AliError("Error occured while loading kinamatics tree.");
769     return retval;
770   }
771  if (fStack) 
772   {
773       fStack->ConnectTree(TreeK());
774       retval = fStack->GetEvent();
775     if ( retval == kFALSE)
776      {
777        AliError("Error occured while loading kinamatics tree.");
778        return retval;
779      }
780     
781   }
782  return 0;
783 }
784 /**************************************************************************/
785
786 Int_t AliRunLoader::OpenDataFile(const TString& filename,TFile*& file,TDirectory*& dir,Option_t* opt,Int_t cl)
787 {
788 //Opens File with kinematics
789  if (file)
790   {
791     if (file->IsOpen() == kFALSE)
792      {//pointer is not null but file is not opened
793        AliWarning("Pointer to file is not null, but file is not opened");//risky any way
794        delete file;
795        file = 0x0; //proceed with opening procedure
796      }
797     else
798      { 
799        AliWarning(Form("File  %s already opened",filename.Data()));
800        return 0;
801      }
802   }
803 //try to find if that file is opened somewere else
804  file = (TFile *)( gROOT->GetListOfFiles()->FindObject(filename) );
805  if (file)
806   {
807    if(file->IsOpen() == kTRUE)
808     {
809      AliWarning(Form("File %s already opened by sombody else.",file->GetName()));
810      return 0;
811     }
812   }
813
814  file = TFile::Open(filename,opt);
815  if (file == 0x0)
816   {//file is null
817     AliError(Form("Can not open file %s",filename.Data()));
818     return 1;
819   }
820  if (file->IsOpen() == kFALSE)
821   {//file is not opened
822     AliError(Form("Can not open file %s",filename.Data()));
823    return 1;
824   }
825   
826  file->SetCompressionLevel(cl);
827  
828  dir = AliLoader::ChangeDir(file,fCurrentEvent);
829  if (dir == 0x0)
830   {
831     AliError(Form("Can not change to root directory in file %s",filename.Data()));
832     return 3;
833   }
834  return 0; 
835 }
836 /**************************************************************************/
837
838 TTree* AliRunLoader::TreeE() const
839 {
840  //returns the tree from folder; shortcut method
841  if (AliDebugLevel() > 10) fEventFolder->ls();
842  TObject *obj = fEventFolder->FindObject(fgkHeaderContainerName);
843  return (obj)?dynamic_cast<TTree*>(obj):0x0;
844 }
845 /**************************************************************************/
846
847 TTree* AliRunLoader::TreeCT() const
848 {
849  //returns the tree from folder; shortcut method
850    if (AliDebugLevel() > 10) fEventFolder->ls();
851    TObject *obj = fEventFolder->FindObject(fgkTriggerContainerName);
852    return (obj)?dynamic_cast<TTree*>(obj):0x0;
853 }
854 /**************************************************************************/
855
856 AliHeader* AliRunLoader::GetHeader() const
857 {
858 //returns pointer header object
859  return fHeader;
860 }
861 /**************************************************************************/
862
863 AliCentralTrigger* AliRunLoader::GetTrigger() const
864 {
865 //returns pointer trigger object
866    return fCTrigger;
867 }
868
869 /**************************************************************************/
870  
871 TTree* AliRunLoader::TreeK() const
872 {
873  //returns the tree from folder; shortcut method
874  TObject *obj = GetEventFolder()->FindObject(fgkKineContainerName);
875  return (obj)?dynamic_cast<TTree*>(obj):0x0;
876 }
877 /**************************************************************************/
878
879 TTree* AliRunLoader::TreeTR() const
880 {
881  //returns the tree from folder; shortcut method
882  TObject* obj = GetEventFolder()->FindObject(fgkTrackRefsContainerName);
883  return (obj)?dynamic_cast<TTree*>(obj):0x0;
884 }
885 /**************************************************************************/
886
887 AliRun* AliRunLoader::GetAliRun() const
888 {
889 //returns AliRun which sits in the folder
890  if (fEventFolder == 0x0) return 0x0;
891  TObject *obj = fEventFolder->FindObject(fgkGAliceName);
892  return (obj)?dynamic_cast<AliRun*>(obj):0x0;
893 }
894 /**************************************************************************/
895
896 Int_t AliRunLoader::WriteHeader(Option_t* opt)
897 {
898 //writes treeE
899   AliDebug(1, "WRITING HEADER");
900   
901   TTree* tree = TreeE();
902   if ( tree == 0x0)
903    {
904      AliWarning("Can not find Header Tree in Folder");
905      return 0;
906    } 
907   if (fGAFile->IsWritable() == kFALSE)
908    {
909      AliError(Form("File %s is not writable",fGAFile->GetName()));
910      return 1;
911    }
912
913   TObject* obj = fGAFile->Get(fgkHeaderContainerName);
914   if (obj)
915    { //if they exist, see if option OVERWRITE is used
916      TString tmp(opt);
917      if(tmp.Contains("OVERWRITE",TString::kIgnoreCase) == 0)
918       {//if it is not used -  give an error message and return an error code
919         AliError("Tree already exisists. Use option \"OVERWRITE\" to overwrite previous data");
920         return 3;
921       }
922    }
923   fGAFile->cd();
924   tree->SetDirectory(fGAFile);
925   tree->Write(0,TObject::kOverwrite);
926
927   AliDebug(1, "WRITTEN\n\n");
928   
929   return 0;
930 }
931
932 /**************************************************************************/
933
934 Int_t AliRunLoader::WriteTrigger(Option_t* opt)
935 {
936    //writes TreeCT
937    AliDebug( 1, "WRITING TRIGGER" );
938   
939    TTree* tree = TreeCT();
940    if ( tree == 0x0) {
941       AliWarning("Can not find Trigger Tree in Folder");
942       return 0;
943    }
944
945    TFile* file = gROOT->GetFile( gSystem->ConcatFileName( fUnixDirName.Data(), fgkDefaultTriggerFileName.Data() ) ) ;
946    if( !file || !file->IsOpen() ) {
947       AliError( "can't write Trigger, file is not open" );
948       return kFALSE;
949    }
950
951    TObject* obj = file->Get( fgkTriggerContainerName );
952    if( obj ) { //if they exist, see if option OVERWRITE is used
953       TString tmp(opt);
954       if( tmp.Contains( "OVERWRITE", TString::kIgnoreCase ) == 0) {
955          //if it is not used -  give an error message and return an error code
956          AliError( "Tree already exisists. Use option \"OVERWRITE\" to overwrite previous data" );
957          return 3;
958       }
959    }
960    file->cd();
961    fCTrigger->Write( 0, TObject::kOverwrite );
962    tree->Write( 0, TObject::kOverwrite );
963    file->Flush();
964
965    AliDebug(1, "WRITTEN\n\n");
966   
967    return 0;
968 }
969 /**************************************************************************/
970
971 Int_t AliRunLoader::WriteAliRun(Option_t* /*opt*/)
972 {
973 //writes AliRun object to the file
974   fGAFile->cd();
975   if (GetAliRun()) GetAliRun()->Write();
976   return 0;
977 }
978 /**************************************************************************/
979
980 Int_t AliRunLoader::WriteKinematics(Option_t* opt)
981 {
982 //writes Kinematics
983   return fKineDataLoader->GetBaseLoader(0)->WriteData(opt);
984 }
985 /**************************************************************************/
986 Int_t AliRunLoader::WriteTrackRefs(Option_t* opt)
987 {
988 //writes Track References tree
989   return fTrackRefsDataLoader->GetBaseLoader(0)->WriteData(opt);
990 }
991 /**************************************************************************/
992
993 Int_t AliRunLoader::WriteHits(Option_t* opt)
994 {
995 //Calls WriteHits for all loaders
996   Int_t res;
997   Int_t result = 0;
998   TIter next(fLoaders);
999   AliLoader *loader;
1000   while((loader = (AliLoader*)next()))
1001    {
1002      res = loader->WriteHits(opt);
1003      if (res)
1004       {
1005         AliError(Form("Failed to write hits for %s (%d)",loader->GetDetectorName().Data(),res));
1006         result = 1;
1007       }
1008    }
1009   return result;
1010 }
1011 /**************************************************************************/
1012
1013 Int_t AliRunLoader::WriteSDigits(Option_t* opt)
1014 {
1015 //Calls WriteSDigits for all loaders
1016   Int_t res;
1017   Int_t result = 0;
1018   TIter next(fLoaders);
1019   AliLoader *loader;
1020   while((loader = (AliLoader*)next()))
1021    {
1022      res = loader->WriteSDigits(opt);
1023      if (res)
1024       {
1025         AliError(Form("Failed to write summable digits for %s.",loader->GetDetectorName().Data()));
1026         result = 1;
1027       }
1028    }
1029   return result;
1030 }
1031 /**************************************************************************/
1032
1033 Int_t AliRunLoader::WriteDigits(Option_t* opt)
1034 {
1035 //Calls WriteDigits for all loaders
1036   Int_t res;
1037   Int_t result = 0;
1038   TIter next(fLoaders);
1039   AliLoader *loader;
1040   while((loader = (AliLoader*)next()))
1041    { 
1042      res = loader->WriteDigits(opt);
1043      if (res)
1044       {
1045         AliError(Form("Failed to write digits for %s.",loader->GetDetectorName().Data()));
1046         result = 1;
1047       }
1048    }
1049   return result;
1050 }
1051 /**************************************************************************/
1052
1053 Int_t AliRunLoader::WriteRecPoints(Option_t* opt)
1054 {
1055 //Calls WriteRecPoints for all loaders
1056   Int_t res;
1057   Int_t result = 0;
1058   TIter next(fLoaders);
1059   AliLoader *loader;
1060   while((loader = (AliLoader*)next()))
1061    {
1062      res = loader->WriteRecPoints(opt);
1063      if (res)
1064       {
1065         AliError(Form("Failed to write Reconstructed Points for %s.",
1066                       loader->GetDetectorName().Data()));
1067         result = 1;
1068       }
1069    }
1070   return result;
1071 }
1072 /**************************************************************************/
1073
1074 Int_t AliRunLoader::WriteTracks(Option_t* opt)
1075 {
1076 //Calls WriteTracks for all loaders
1077   Int_t res;
1078   Int_t result = 0;
1079   TIter next(fLoaders);
1080   AliLoader *loader;
1081   while((loader = (AliLoader*)next()))
1082    {
1083      res = loader->WriteTracks(opt);
1084      if (res)
1085       {
1086         AliError(Form("Failed to write Tracks for %s.",
1087                       loader->GetDetectorName().Data()));
1088         result = 1;
1089       }
1090    }
1091   return result;
1092 }
1093 /**************************************************************************/
1094
1095 Int_t AliRunLoader::WriteRunLoader(Option_t* /*opt*/)
1096 {
1097 //Writes itself to the file
1098   CdGAFile();
1099   this->Write(0,TObject::kOverwrite);
1100   return 0;
1101 }
1102 /**************************************************************************/
1103
1104 Int_t AliRunLoader::SetEventFolderName(const TString& name)
1105 {  
1106 //sets top folder name for this run; of alread
1107   if (name.IsNull())
1108    {
1109      AliError("Name is empty");
1110      return 1;
1111    }
1112   
1113   //check if such a folder already exists - try to find it in alice top folder
1114   TObject* obj = AliConfig::Instance()->GetTopFolder()->FindObject(name);
1115   if(obj)
1116    {
1117      TFolder* fold = dynamic_cast<TFolder*>(obj);
1118      if (fold == 0x0)
1119       {
1120        AliError("Such a obejct already exists in top alice folder and it is not a folder.");
1121        return 2;
1122       }
1123      //folder which was found is our folder
1124      if (fEventFolder == fold)
1125       {
1126        return 0;
1127       }
1128      else
1129       {
1130        AliError("Such a folder already exists in top alice folder. Can not mount.");
1131        return 2;
1132       }
1133    }
1134
1135   //event is alredy connected, just change name of the folder
1136   if (fEventFolder) 
1137    {
1138      fEventFolder->SetName(name);
1139      return 0;
1140    }
1141
1142   if (fKineDataLoader == 0x0)
1143     fKineDataLoader = new AliDataLoader(fgkDefaultKineFileName,fgkKineContainerName,"Kinematics");
1144
1145   if ( fTrackRefsDataLoader == 0x0)
1146     fTrackRefsDataLoader = new AliDataLoader(fgkDefaultTrackRefsFileName,fgkTrackRefsContainerName,"Track References");
1147    
1148   //build the event folder structure
1149   AliDebug(1, Form("Creating new event folder named %s",name.Data()));
1150   fEventFolder = AliConfig::Instance()->BuildEventFolder(name,"Event Folder");
1151   fEventFolder->Add(this);//put myself to the folder to accessible for all
1152   
1153   TIter next(fLoaders);
1154   AliLoader *loader;
1155   while((loader = (AliLoader*)next()))
1156    {
1157      loader->Register(fEventFolder);//build folder structure for this detector
1158    }
1159   
1160   fKineDataLoader->SetEventFolder(GetEventFolder());
1161   fTrackRefsDataLoader->SetEventFolder(GetEventFolder());
1162   fKineDataLoader->SetFolder(GetEventFolder());
1163   fTrackRefsDataLoader->SetFolder(GetEventFolder());
1164   
1165   fEventFolder->SetOwner();
1166   return 0;
1167 }
1168 /**************************************************************************/
1169
1170 void AliRunLoader::AddLoader(AliLoader* loader)
1171  {
1172  //Adds the Loader for given detector 
1173   if (loader == 0x0) //if null shout and exit
1174    {
1175      AliError("Parameter is NULL");
1176      return;
1177    }
1178   loader->SetDirName(fUnixDirName);
1179   if (fEventFolder) loader->SetEventFolder(fEventFolder); //if event folder is already defined, 
1180                                                           //pass information to the Loader
1181   fLoaders->Add(loader);//add the Loader to the array
1182  }
1183 /**************************************************************************/
1184
1185 void AliRunLoader::AddLoader(AliDetector* det)
1186  {
1187 //Asks module (detector) ro make a Loader and stores in the array
1188    if (det == 0x0) return;
1189    AliLoader* get = det->GetLoader();//try to get loader
1190    if (get == 0x0)  get = det->MakeLoader(fEventFolder->GetName());//if did not obtain, ask to make it
1191
1192    if (get) 
1193     {
1194       AliDebug(1, Form("Detector: %s   Loader : %s",det->GetName(),get->GetName()));
1195       AddLoader(get);
1196     }
1197  }
1198
1199 /**************************************************************************/
1200
1201 AliLoader* AliRunLoader::GetLoader(const char* detname) const
1202 {
1203 //returns loader for given detector
1204 //note that naming convention is TPCLoader not just TPC
1205   return (AliLoader*)fLoaders->FindObject(detname);
1206 }
1207
1208 /**************************************************************************/
1209
1210 AliLoader* AliRunLoader::GetLoader(AliDetector* det) const
1211 {
1212 //get loader for detector det
1213  if(det == 0x0) return 0x0;
1214  TString getname(det->GetName());
1215  getname+="Loader";
1216  AliDebug(1, Form(" Loader name is %s",getname.Data()));
1217  return GetLoader(getname);
1218 }
1219
1220 /**************************************************************************/
1221
1222 void AliRunLoader::CleanFolders()
1223 {
1224 //  fEventFolder->Add(this);//put myself to the folder to accessible for all
1225
1226   CleanDetectors();
1227   CleanHeader();
1228   CleanKinematics();
1229   CleanTrigger();
1230 }
1231 /**************************************************************************/
1232
1233 void AliRunLoader::CleanDetectors()
1234 {
1235 //Calls CleanFolders for all detectors
1236   TIter next(fLoaders);
1237   AliLoader *loader;
1238   while((loader = (AliLoader*)next())) 
1239    {
1240      loader->CleanFolders();
1241    }
1242 }
1243 /**************************************************************************/
1244
1245 void AliRunLoader::RemoveEventFolder()
1246 {
1247 //remove all the tree of event 
1248 //all the stuff changing EbE stays untached (PDGDB, tasks, etc.)
1249
1250  if (fEventFolder == 0x0) return;
1251  fEventFolder->SetOwner(kFALSE);//don't we want to deleted while removing the folder that we are sitting in
1252  fEventFolder->Remove(this);//remove us drom folder
1253  
1254  AliConfig::Instance()->GetTopFolder()->SetOwner(); //brings ownership back for fEventFolder since it sits in top folder
1255  AliConfig::Instance()->GetTopFolder()->Remove(fEventFolder); //remove the event tree
1256  delete fEventFolder;
1257 }
1258 /**************************************************************************/
1259
1260 void AliRunLoader::SetGAliceFile(TFile* gafile)
1261 {
1262 //sets pointer to galice.root file
1263  fGAFile = gafile;
1264 }
1265
1266 /**************************************************************************/
1267
1268 Int_t AliRunLoader::LoadHits(Option_t* detectors,Option_t* opt)
1269 {
1270 //LoadHits in selected detectors i.e. detectors="ITS TPC TRD" or "all"
1271
1272   AliDebug(1, "Loading Hits");
1273   TObjArray* loaders;
1274   TObjArray arr;
1275
1276   const char* oAll = strstr(detectors,"all");
1277   if (oAll)
1278    {
1279      AliDebug(1, "Option is All");
1280      loaders = fLoaders;
1281    }
1282   else
1283    {
1284      GetListOfDetectors(detectors,arr);//this method looks for all Loaders corresponding to names (many) specified in detectors option
1285      loaders = &arr;//get the pointer array
1286    }   
1287
1288   AliDebug(1, Form("For detectors. Number of detectors chosen for loading %d",loaders->GetEntries()));
1289   
1290   TIter next(loaders);
1291   AliLoader *loader;
1292   while((loader = (AliLoader*)next())) 
1293    {
1294     AliDebug(1, Form("    Calling LoadHits(%s) for %s",opt,loader->GetName()));
1295     loader->LoadHits(opt);
1296    }
1297   AliDebug(1, "Done");
1298   return 0;
1299
1300
1301 /**************************************************************************/
1302
1303 Int_t AliRunLoader::LoadSDigits(Option_t* detectors,Option_t* opt)
1304 {
1305 //LoadHits in selected detectors i.e. detectors="ITS TPC TRD" or "all"
1306
1307   TObjArray* loaders;
1308   TObjArray arr;
1309
1310   const char* oAll = strstr(detectors,"all");
1311   if (oAll)
1312    {
1313      loaders = fLoaders;
1314    }
1315   else
1316    {
1317      GetListOfDetectors(detectors,arr);//this method looks for all Loaders corresponding to names (many) specified in detectors option
1318      loaders = &arr;//get the pointer to array
1319    }   
1320
1321   TIter next(loaders);
1322   AliLoader *loader;
1323   while((loader = (AliLoader*)next())) 
1324    {
1325     loader->LoadSDigits(opt);
1326    }
1327   return 0;
1328
1329
1330 /**************************************************************************/
1331
1332 Int_t AliRunLoader::LoadDigits(Option_t* detectors,Option_t* opt)
1333 {
1334 //LoadHits in selected detectors i.e. detectors="ITS TPC TRD" or "all"
1335
1336   TObjArray* loaders;
1337   TObjArray arr;
1338
1339   const char* oAll = strstr(detectors,"all");
1340   if (oAll)
1341    {
1342      loaders = fLoaders;
1343    }
1344   else
1345    {
1346      GetListOfDetectors(detectors,arr);//this method looks for all Loaders corresponding to names (many) specified in detectors option
1347      loaders = &arr;//get the pointer array
1348    }   
1349
1350   TIter next(loaders);
1351   AliLoader *loader;
1352   while((loader = (AliLoader*)next())) 
1353    {
1354     loader->LoadDigits(opt);
1355    }
1356   return 0;
1357
1358 /**************************************************************************/
1359
1360 Int_t AliRunLoader::LoadRecPoints(Option_t* detectors,Option_t* opt)
1361 {
1362 //LoadHits in selected detectors i.e. detectors="ITS TPC TRD" or "all"
1363
1364   TObjArray* loaders;
1365   TObjArray arr;
1366
1367   const char* oAll = strstr(detectors,"all");
1368   if (oAll)
1369    {
1370      loaders = fLoaders;
1371    }
1372   else
1373    {
1374      GetListOfDetectors(detectors,arr);//this method looks for all Loaders corresponding to names (many) specified in detectors option
1375      loaders = &arr;//get the pointer array
1376    }   
1377
1378   TIter next(loaders);
1379   AliLoader *loader;
1380   while((loader = (AliLoader*)next())) 
1381    {
1382     loader->LoadRecPoints(opt);
1383    }
1384   return 0;
1385
1386 /**************************************************************************/
1387
1388 Int_t AliRunLoader::LoadRecParticles(Option_t* detectors,Option_t* opt)
1389 {
1390 //LoadHits in selected detectors i.e. detectors="ITS TPC TRD" or "all"
1391
1392   TObjArray* loaders;
1393   TObjArray arr;
1394
1395   const char* oAll = strstr(detectors,"all");
1396   if (oAll)
1397    {
1398      loaders = fLoaders;
1399    }
1400   else
1401    {
1402      GetListOfDetectors(detectors,arr);//this method looks for all Loaders corresponding to names (many) specified in detectors option
1403      loaders = &arr;//get the pointer array
1404    }   
1405
1406   TIter next(loaders);
1407   AliLoader *loader;
1408   while((loader = (AliLoader*)next())) 
1409    {
1410     loader->LoadRecParticles(opt);
1411    }
1412   return 0;
1413
1414 /**************************************************************************/
1415
1416 Int_t AliRunLoader::LoadTracks(Option_t* detectors,Option_t* opt)
1417 {
1418 //LoadHits in selected detectors i.e. detectors="ITS TPC TRD" or "all"
1419
1420   TObjArray* loaders;
1421   TObjArray arr;
1422
1423   const char* oAll = strstr(detectors,"all");
1424   if (oAll)
1425    {
1426      loaders = fLoaders;
1427    }
1428   else
1429    {
1430      GetListOfDetectors(detectors,arr);//this method looks for all Loaders corresponding to names (many) specified in detectors option
1431      loaders = &arr;//get the pointer array
1432    }   
1433
1434   TIter next(loaders);
1435   AliLoader *loader;
1436   while((loader = (AliLoader*)next())) 
1437    {
1438     loader->LoadTracks(opt);
1439    }
1440   return 0;
1441
1442 /**************************************************************************/
1443
1444 void AliRunLoader::UnloadHits(Option_t* detectors)
1445 {
1446   //unloads hits for detectors specified in parameter
1447   TObjArray* loaders;
1448   TObjArray arr;
1449
1450   const char* oAll = strstr(detectors,"all");
1451   if (oAll)
1452    {
1453      loaders = fLoaders;
1454    }
1455   else
1456    {
1457      GetListOfDetectors(detectors,arr);//this method looks for all Loaders corresponding to names (many) specified in detectors option
1458      loaders = &arr;//get the pointer to array
1459    }   
1460
1461   TIter next(loaders);
1462   AliLoader *loader;
1463   while((loader = (AliLoader*)next())) 
1464    {
1465     loader->UnloadHits();
1466    }
1467 }
1468 /**************************************************************************/
1469
1470 void AliRunLoader::UnloadSDigits(Option_t* detectors)
1471 {
1472   //unloads SDigits for detectors specified in parameter
1473   TObjArray* loaders;
1474   TObjArray arr;
1475
1476   const char* oAll = strstr(detectors,"all");
1477   if (oAll)
1478    {
1479      loaders = fLoaders;
1480    }
1481   else
1482    {
1483      GetListOfDetectors(detectors,arr);//this method looks for all Loaders corresponding to names (many) specified in detectors option
1484      loaders = &arr;//get the pointer to array
1485    }   
1486
1487   TIter next(loaders);
1488   AliLoader *loader;
1489   while((loader = (AliLoader*)next())) 
1490    {
1491     loader->UnloadSDigits();
1492    }
1493 }
1494 /**************************************************************************/
1495
1496 void AliRunLoader::UnloadDigits(Option_t* detectors)
1497 {
1498   //unloads Digits for detectors specified in parameter
1499   TObjArray* loaders;
1500   TObjArray arr;
1501
1502   const char* oAll = strstr(detectors,"all");
1503   if (oAll)
1504    {
1505      loaders = fLoaders;
1506    }
1507   else
1508    {
1509      GetListOfDetectors(detectors,arr);//this method looks for all Loaders corresponding to names (many) specified in detectors option
1510      loaders = &arr;//get the pointer to array
1511    }   
1512
1513   TIter next(loaders);
1514   AliLoader *loader;
1515   while((loader = (AliLoader*)next())) 
1516    {
1517     loader->UnloadDigits();
1518    }
1519 }
1520 /**************************************************************************/
1521
1522 void AliRunLoader::UnloadRecPoints(Option_t* detectors)
1523 {
1524   //unloads RecPoints for detectors specified in parameter
1525   TObjArray* loaders;
1526   TObjArray arr;
1527
1528   const char* oAll = strstr(detectors,"all");
1529   if (oAll)
1530    {
1531      loaders = fLoaders;
1532    }
1533   else
1534    {
1535      GetListOfDetectors(detectors,arr);//this method looks for all Loaders corresponding to names (many) specified in detectors option
1536      loaders = &arr;//get the pointer to array
1537    }   
1538
1539   TIter next(loaders);
1540   AliLoader *loader;
1541   while((loader = (AliLoader*)next())) 
1542    {
1543     loader->UnloadRecPoints();
1544    }
1545 }
1546 /**************************************************************************/
1547
1548 void AliRunLoader::UnloadAll(Option_t* detectors)
1549 {
1550   //calls UnloadAll for detectors names specified in parameter
1551   // option "all" passed can be passed
1552   TObjArray* loaders;
1553   TObjArray arr;
1554
1555   const char* oAll = strstr(detectors,"all");
1556   if (oAll)
1557    {
1558      loaders = fLoaders;
1559    }
1560   else
1561    {
1562      GetListOfDetectors(detectors,arr);//this method looks for all Loaders corresponding to names (many) specified in detectors option
1563      loaders = &arr;//get the pointer to array
1564    }   
1565
1566   TIter next(loaders);
1567   AliLoader *loader;
1568   while((loader = (AliLoader*)next())) 
1569    {
1570     loader->UnloadAll();
1571    }
1572 }
1573 /**************************************************************************/
1574
1575 void AliRunLoader::UnloadTracks(Option_t* detectors)
1576 {
1577   //unloads Tracks for detectors specified in parameter
1578   TObjArray* loaders;
1579   TObjArray arr;
1580
1581   const char* oAll = strstr(detectors,"all");
1582   if (oAll)
1583    {
1584      loaders = fLoaders;
1585    }
1586   else
1587    {
1588      GetListOfDetectors(detectors,arr);//this method looks for all Loaders corresponding to names (many) specified in detectors option
1589      loaders = &arr;//get the pointer to array
1590    }   
1591
1592   TIter next(loaders);
1593   AliLoader *loader;
1594   while((loader = (AliLoader*)next())) 
1595    {
1596     loader->UnloadTracks();
1597    }
1598 }
1599 /**************************************************************************/
1600
1601 void AliRunLoader::UnloadRecParticles(Option_t* detectors)
1602 {
1603   //unloads Particles for detectors specified in parameter
1604   TObjArray* loaders;
1605   TObjArray arr;
1606
1607   const char* oAll = strstr(detectors,"all");
1608   if (oAll)
1609    {
1610      loaders = fLoaders;
1611    }
1612   else
1613    {
1614      GetListOfDetectors(detectors,arr);//this method looks for all Loaders corresponding to names (many) specified in detectors option
1615      loaders = &arr;//get the pointer to array
1616    }   
1617
1618   TIter next(loaders);
1619   AliLoader *loader;
1620   while((loader = (AliLoader*)next())) 
1621    {
1622     loader->UnloadRecParticles();
1623    }
1624 }
1625 /**************************************************************************/
1626
1627 AliRunLoader* AliRunLoader::GetRunLoader(const char* eventfoldername)
1628 {
1629 //returns RunLoader from folder named eventfoldername
1630   TFolder* evfold= dynamic_cast<TFolder*>(AliConfig::Instance()->GetTopFolder()->FindObject(eventfoldername));
1631   if (evfold == 0x0)
1632    {
1633      return 0x0;
1634    }
1635   AliRunLoader* runget = dynamic_cast<AliRunLoader*>(evfold->FindObject(AliRunLoader::fgkRunLoaderName));
1636   return runget;
1637   
1638 }
1639 /**************************************************************************/
1640
1641 AliLoader* AliRunLoader::GetDetectorLoader(const char* detname, const char* eventfoldername)
1642 {
1643 //get the loader of the detector with the given name from the global
1644 //run loader object
1645   AliRunLoader* runLoader = GetRunLoader(eventfoldername);
1646   if (!runLoader) {
1647     AliErrorClass("No run loader found");
1648     return NULL;
1649   }
1650   return runLoader->GetDetectorLoader(detname);
1651 }
1652 /**************************************************************************/
1653
1654 AliLoader* AliRunLoader::GetDetectorLoader(const char* detname)
1655 {
1656 //get the loader of the detector with the given name from the global
1657 //run loader object
1658   
1659   char loadername[256];
1660   sprintf(loadername, "%sLoader", detname);
1661   AliLoader* loader = GetLoader(loadername);
1662   if (!loader) {
1663     AliError(Form("No loader for %s found", detname));
1664     return NULL;
1665   }
1666   return loader;
1667 }
1668 /**************************************************************************/
1669
1670 TTree* AliRunLoader::GetTreeH(const char* detname, Bool_t maketree, const char* eventfoldername)
1671 {
1672 //get the tree with hits of the detector with the given name
1673 //if maketree is true and the tree does not exist, the tree is created
1674   AliLoader* loader = GetDetectorLoader(detname,eventfoldername);
1675   if (!loader) return NULL;
1676   if (!loader->TreeH() && maketree) loader->MakeTree("H");
1677   return loader->TreeH();
1678 }
1679
1680 /**************************************************************************/
1681
1682 TTree* AliRunLoader::GetTreeH(const char* detname, Bool_t maketree)
1683 {
1684 //get the tree with hits of the detector with the given name
1685 //if maketree is true and the tree does not exist, the tree is created
1686   AliLoader* loader = GetDetectorLoader(detname);
1687   if (!loader) return NULL;
1688   if (!loader->TreeH() && maketree) loader->MakeTree("H");
1689   return loader->TreeH();
1690 }
1691 /**************************************************************************/
1692
1693 TTree* AliRunLoader::GetTreeS(const char* detname, Bool_t maketree,const char* eventfoldername)
1694 {
1695 //get the tree with summable digits of the detector with the given name
1696 //if maketree is true and the tree does not exist, the tree is created
1697   AliLoader* loader = GetDetectorLoader(detname,eventfoldername);
1698   if (!loader) return NULL;
1699   if (!loader->TreeS() && maketree) loader->MakeTree("S");
1700   return loader->TreeS();
1701 }
1702 /**************************************************************************/
1703
1704 TTree* AliRunLoader::GetTreeS(const char* detname, Bool_t maketree)
1705 {
1706 //get the tree with summable digits of the detector with the given name
1707 //if maketree is true and the tree does not exist, the tree is created
1708   AliLoader* loader = GetDetectorLoader(detname);
1709   if (!loader) return NULL;
1710   if (!loader->TreeS() && maketree) loader->MakeTree("S");
1711   return loader->TreeS();
1712 }
1713 /**************************************************************************/
1714
1715 TTree* AliRunLoader::GetTreeD(const char* detname, Bool_t maketree,const char* eventfoldername)
1716 {
1717 //get the tree with digits of the detector with the given name
1718 //if maketree is true and the tree does not exist, the tree is created
1719   AliLoader* loader = GetDetectorLoader(detname,eventfoldername);
1720   if (!loader) return NULL;
1721   if (!loader->TreeD() && maketree) loader->MakeTree("D");
1722   return loader->TreeD();
1723 }
1724 /**************************************************************************/
1725
1726 TTree* AliRunLoader::GetTreeD(const char* detname, Bool_t maketree)
1727 {
1728 //get the tree with digits of the detector with the given name
1729 //if maketree is true and the tree does not exist, the tree is created
1730   AliLoader* loader = GetDetectorLoader(detname);
1731   if (!loader) return NULL;
1732   if (!loader->TreeD() && maketree) loader->MakeTree("D");
1733   return loader->TreeD();
1734 }
1735 /**************************************************************************/
1736 TTree* AliRunLoader::GetTreeR(const char* detname, Bool_t maketree,const char* eventfoldername)
1737 {
1738 //get the tree with clusters of the detector with the given name
1739 //if maketree is true and the tree does not exist, the tree is created
1740   AliLoader* loader = GetDetectorLoader(detname,eventfoldername);
1741   if (!loader) return NULL;
1742   if (!loader->TreeR() && maketree) loader->MakeTree("R");
1743   return loader->TreeR();
1744 }
1745 /**************************************************************************/
1746
1747 TTree* AliRunLoader::GetTreeR(const char* detname, Bool_t maketree)
1748 {
1749 //get the tree with clusters of the detector with the given name
1750 //if maketree is true and the tree does not exist, the tree is created
1751   AliLoader* loader = GetDetectorLoader(detname);
1752   if (!loader) return NULL;
1753   if (!loader->TreeR() && maketree) loader->MakeTree("R");
1754   return loader->TreeR();
1755 }
1756 /**************************************************************************/
1757
1758 TTree* AliRunLoader::GetTreeT(const char* detname, Bool_t maketree,const char* eventfoldername)
1759 {
1760 //get the tree with tracks of the detector with the given name
1761 //if maketree is true and the tree does not exist, the tree is created
1762   AliLoader* loader = GetDetectorLoader(detname,eventfoldername);
1763   if (!loader) return NULL;
1764   if (!loader->TreeT() && maketree) loader->MakeTree("T");
1765   return loader->TreeT();
1766 }
1767 /**************************************************************************/
1768
1769 TTree* AliRunLoader::GetTreeT(const char* detname, Bool_t maketree)
1770 {
1771 //get the tree with tracks of the detector with the given name
1772 //if maketree is true and the tree does not exist, the tree is created
1773   AliLoader* loader = GetDetectorLoader(detname);
1774   if (!loader) return NULL;
1775   if (!loader->TreeT() && maketree) loader->MakeTree("T");
1776   return loader->TreeT();
1777 }
1778 /**************************************************************************/
1779
1780 TTree* AliRunLoader::GetTreeP(const char* detname, Bool_t maketree,const char* eventfoldername)
1781 {
1782 //get the tree with particles of the detector with the given name
1783 //if maketree is true and the tree does not exist, the tree is created
1784   AliLoader* loader = GetDetectorLoader(detname,eventfoldername);
1785   if (!loader) return NULL;
1786   if (!loader->TreeP() && maketree) loader->MakeTree("P");
1787   return loader->TreeP();
1788 }
1789 /**************************************************************************/
1790
1791 TTree* AliRunLoader::GetTreeP(const char* detname, Bool_t maketree)
1792 {
1793 //get the tree with particles of the detector with the given name
1794 //if maketree is true and the tree does not exist, the tree is created
1795   AliLoader* loader = GetDetectorLoader(detname);
1796   if (!loader) return NULL;
1797   if (!loader->TreeP() && maketree) loader->MakeTree("P");
1798   return loader->TreeP();
1799 }
1800
1801 /**************************************************************************/
1802
1803 void AliRunLoader::CdGAFile()
1804 {
1805 //sets gDirectory to galice file
1806 //work around 
1807   if(fGAFile) fGAFile->cd();
1808 }
1809  
1810 /**************************************************************************/
1811
1812 void AliRunLoader::GetListOfDetectors(const char * namelist,TObjArray& pointerarray) const
1813  {
1814 //this method looks for all Loaders corresponding 
1815 //to names (many) specified in namelist i.e. namelist ("ITS TPC TRD")
1816   
1817    char buff[10];
1818    char dets [200];
1819    strcpy(dets,namelist);//compiler cries when char* = const Option_t*;
1820    dets[strlen(dets)+1] = '\n';//set endl at the end of string 
1821    char* pdet = dets;
1822    Int_t tmp;
1823    for(;;)
1824     {
1825       tmp = sscanf(pdet,"%s",buff);//read the string from the input string pdet into buff
1826       if ( (buff[0] == 0) || (tmp == 0) ) break; //if not read
1827      
1828       pdet = strstr(pdet,buff) + strlen(buff);//move the input pointer about number of bytes (letters) read
1829       //I am aware that is a little complicated. I don't know the number of spaces between detector names
1830       //so I read the string, than I find where it starts (strstr) and move the pointer about length of a string
1831       //If there is a better way, please write me (Piotr.Skowronski@cern.ch)
1832       //construct the Loader name
1833       TString getname(buff);
1834       getname+="Loader";
1835       AliLoader* loader = GetLoader(getname);//get the Loader
1836       if (loader)
1837        {
1838         pointerarray.Add(loader);
1839        }
1840       else
1841        {
1842         AliError(Form("Can not find Loader for %s",buff));
1843        }
1844         
1845       buff[0] = 0;
1846     }
1847  }
1848 /*****************************************************************************/ 
1849
1850 void AliRunLoader::Clean(const TString& name)
1851 {
1852 //removes object with given name from event folder and deletes it
1853   if (GetEventFolder() == 0x0) return;
1854   TObject* obj = GetEventFolder()->FindObject(name);
1855   if(obj)
1856    {
1857      AliDebug(1, Form("name=%s, cleaning %s.",GetName(),name.Data()));
1858      GetEventFolder()->Remove(obj);
1859      delete obj;
1860      obj = 0x0;
1861    }
1862 }
1863
1864 /*****************************************************************************/ 
1865
1866 TTask* AliRunLoader::GetRunDigitizer()
1867 {
1868 //returns Run Digitizer from folder
1869
1870  TFolder* topf = AliConfig::Instance()->GetTaskFolder();
1871  TObject* obj = topf->FindObjectAny(AliConfig::Instance()->GetDigitizerTaskName());
1872  return (obj)?dynamic_cast<TTask*>(obj):0x0;
1873 }
1874 /*****************************************************************************/ 
1875
1876 TTask* AliRunLoader::GetRunSDigitizer()
1877 {
1878 //returns SDigitizer Task from folder
1879
1880  TFolder* topf = AliConfig::Instance()->GetTaskFolder();
1881  TObject* obj = topf->FindObjectAny(AliConfig::Instance()->GetSDigitizerTaskName());
1882  return (obj)?dynamic_cast<TTask*>(obj):0x0;
1883 }
1884 /*****************************************************************************/ 
1885
1886 TTask* AliRunLoader::GetRunReconstructioner()
1887 {
1888 //returns Reconstructioner Task from folder
1889  TFolder* topf = AliConfig::Instance()->GetTaskFolder();
1890  TObject* obj = topf->FindObjectAny(AliConfig::Instance()->GetReconstructionerTaskName());
1891  return (obj)?dynamic_cast<TTask*>(obj):0x0;
1892 }
1893 /*****************************************************************************/ 
1894
1895 TTask* AliRunLoader::GetRunTracker()
1896 {
1897 //returns Tracker Task from folder
1898  TFolder* topf = AliConfig::Instance()->GetTaskFolder();
1899  TObject* obj = topf->FindObjectAny(AliConfig::Instance()->GetTrackerTaskName());
1900  return (obj)?dynamic_cast<TTask*>(obj):0x0;
1901 }
1902 /*****************************************************************************/ 
1903
1904 TTask* AliRunLoader::GetRunPIDTask()
1905 {
1906 //returns Tracker Task from folder
1907  TFolder* topf = AliConfig::Instance()->GetTaskFolder();
1908  TObject* obj = topf->FindObjectAny(AliConfig::Instance()->GetPIDTaskName());
1909  return (obj)?dynamic_cast<TTask*>(obj):0x0;
1910 }
1911 /*****************************************************************************/ 
1912
1913 TTask* AliRunLoader::GetRunQATask()
1914 {
1915 //returns Quality Assurance Task from folder
1916  TFolder* topf = AliConfig::Instance()->GetTaskFolder();
1917  if (topf == 0x0)
1918   {
1919     AliErrorClass("Can not get task folder from AliConfig");
1920     return 0x0;
1921   }
1922  TObject* obj = topf->FindObjectAny(AliConfig::Instance()->GetQATaskName());
1923  return (obj)?dynamic_cast<TTask*>(obj):0x0;
1924 }
1925
1926 /*****************************************************************************/ 
1927
1928 void AliRunLoader::SetCompressionLevel(Int_t cl)
1929 {
1930 //Sets Compression Level in all files
1931  if (fGAFile) fGAFile->SetCompressionLevel(cl);
1932  SetKineComprLevel(cl);
1933  SetTrackRefsComprLevel(cl);
1934  TIter next(fLoaders);
1935  AliLoader *loader;
1936  while((loader = (AliLoader*)next()))
1937   {
1938    loader->SetCompressionLevel(cl);
1939   }
1940 }
1941 /**************************************************************************/
1942
1943 void AliRunLoader::SetKineComprLevel(Int_t cl)
1944 {
1945 //Sets comression level in Kine File
1946   fKineDataLoader->SetCompressionLevel(cl);
1947 }
1948 /**************************************************************************/
1949
1950 void AliRunLoader::SetTrackRefsComprLevel(Int_t cl)
1951 {
1952 //Sets comression level in Track Refences File
1953   fTrackRefsDataLoader->SetCompressionLevel(cl);
1954 }
1955 /**************************************************************************/
1956
1957 void AliRunLoader::UnloadHeader()
1958 {
1959  //removes TreeE from folder and deletes it
1960  // as well as fHeader object
1961  CleanHeader();
1962  delete fHeader;
1963  fHeader = 0x0;
1964 }
1965 /**************************************************************************/
1966
1967 void AliRunLoader::UnloadTrigger()
1968 {
1969  //removes TreeCT from folder and deletes it
1970  // as well as fHeader object
1971    CleanTrigger();
1972    delete fCTrigger;
1973    fCTrigger = 0x0;
1974 }
1975
1976 /**************************************************************************/
1977
1978 void AliRunLoader::UnloadKinematics()
1979 {
1980 //Unloads Kinematics
1981  fKineDataLoader->GetBaseLoader(0)->Unload();
1982 }
1983 /**************************************************************************/
1984
1985 void AliRunLoader::UnloadTrackRefs()
1986 {
1987 //Unloads Track Refernces
1988  fTrackRefsDataLoader->GetBaseLoader(0)->Unload();
1989 }
1990 /**************************************************************************/
1991
1992 void AliRunLoader::UnloadgAlice()
1993 {
1994 //Unloads gAlice
1995  if (gAlice == GetAliRun())
1996   {
1997    AliDebug(1, "Set gAlice = 0x0");
1998    gAlice = 0x0;//if gAlice is the same that in folder (to be deleted by the way of folder)
1999   }
2000  AliRun* alirun = GetAliRun();
2001  if (GetEventFolder()) GetEventFolder()->Remove(alirun);
2002  delete alirun;
2003 }
2004 /**************************************************************************/
2005
2006 void  AliRunLoader::MakeTrackRefsContainer()
2007 {
2008 // Makes a tree for Track References
2009   fTrackRefsDataLoader->MakeTree();
2010 }
2011 /**************************************************************************/
2012
2013 Int_t AliRunLoader::LoadTrackRefs(Option_t* option)
2014 {
2015 //Load track references from file (opens file and posts tree to folder)
2016
2017  return fTrackRefsDataLoader->GetBaseLoader(0)->Load(option);
2018 }
2019 /**************************************************************************/
2020
2021 void  AliRunLoader::SetDirName(TString& dirname)
2022 {
2023 //sets directory name 
2024   if (dirname.IsNull()) return;
2025   fUnixDirName = dirname;
2026   fKineDataLoader->SetDirName(dirname);
2027   fTrackRefsDataLoader->SetDirName(dirname);
2028   
2029   TIter next(fLoaders);
2030   AliLoader *loader;
2031   while((loader = (AliLoader*)next()))
2032    {
2033     loader->SetDirName(dirname);
2034    }
2035
2036 }
2037 /*****************************************************************************/ 
2038
2039 Int_t AliRunLoader::GetFileOffset() const
2040 {
2041 //returns the file number that is added to the file name for current event
2042   return Int_t(fCurrentEvent/fNEventsPerFile);
2043 }
2044
2045 /*****************************************************************************/ 
2046 const TString AliRunLoader::SetFileOffset(const TString& fname)
2047 {
2048 //adds the the number to the file name at proper place for current event
2049   Long_t offset = (Long_t)GetFileOffset();
2050   if (offset < 1) return fname;
2051   TString soffset;
2052   soffset += offset;//automatic conversion to string
2053   TString dotroot(".root");
2054   const TString& offfsetdotroot = offset + dotroot;
2055   TString out = fname;
2056   out = out.ReplaceAll(dotroot,offfsetdotroot);
2057   AliDebug(1, Form(" in=%s out=%s",fname.Data(),out.Data()));
2058   return out;
2059 }
2060 /*****************************************************************************/ 
2061
2062 void AliRunLoader::SetDigitsFileNameSuffix(const TString& suffix)
2063 {
2064 //adds the suffix before ".root", 
2065 //e.g. TPC.Digits.root -> TPC.DigitsMerged.root
2066 //made on Jiri Chudoba demand
2067
2068   TIter next(fLoaders);
2069   AliLoader *loader;
2070   while((loader = (AliLoader*)next())) 
2071    {
2072      loader->SetDigitsFileNameSuffix(suffix);
2073    }
2074 }
2075 /*****************************************************************************/ 
2076
2077 TString AliRunLoader::GetFileName() const
2078 {
2079 //returns name of galice file
2080  TString result;
2081  if (fGAFile == 0x0) return result;
2082  result = fGAFile->GetName();
2083  return result;
2084 }
2085 /*****************************************************************************/ 
2086
2087 void AliRunLoader::SetDetectorAddresses()
2088 {
2089  //calls SetTreeAddress for all detectors
2090   if (GetAliRun()==0x0) return;
2091   TIter next(GetAliRun()->Modules());
2092   AliModule* mod;
2093   while((mod = (AliModule*)next())) 
2094    {
2095      AliDetector* det = dynamic_cast<AliDetector*>(mod);
2096      if (det) det->SetTreeAddress();
2097    }
2098 }
2099 /*****************************************************************************/ 
2100
2101 void AliRunLoader::Synchronize()
2102 {
2103   //synchrinizes all writtable files 
2104   TIter next(fLoaders);
2105   AliLoader *loader;
2106   while((loader = (AliLoader*)next()))
2107    {
2108      loader->Synchronize();
2109    }
2110   
2111   fKineDataLoader->Synchronize();
2112   fTrackRefsDataLoader->Synchronize();
2113
2114   TFile* file = gROOT->GetFile( gSystem->ConcatFileName( fUnixDirName.Data(), fgkDefaultTriggerFileName.Data() ) ) ;
2115   if( file ) file->Flush();
2116   
2117   if (fGAFile) fGAFile->Flush();
2118 }
2119 /*****************************************************************************/ 
2120 /*****************************************************************************/