]> git.uio.no Git - u/mrichter/AliRoot.git/blob - STEER/AliRunLoader.cxx
Fixed warnings
[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         char* tmp = gSystem->ConcatFileName( fUnixDirName.Data(), fgkDefaultTriggerFileName.Data() );
625         file = TFile::Open(tmp , "RECREATE" ) ;
626         delete[] tmp;
627       }
628
629       file->cd();
630       TTree* tree = new TTree( fgkTriggerContainerName, "Tree with Central Trigger Mask" );
631       GetEventFolder()->Add(tree);
632       MakeTrigger();
633   //    WriteHeader("OVERWRITE");
634    }
635
636   TIter next(fLoaders);
637   AliLoader *loader;
638   while((loader = (AliLoader*)next()))
639    {
640     loader->MakeTree(option);
641    }
642
643 }
644 /**************************************************************************/
645     
646 Int_t AliRunLoader::LoadgAlice()
647 {
648 //Loads gAlice from file
649  if (GetAliRun())
650   {
651     AliWarning("AliRun is already in folder. Unload first.");
652     return 0;
653   }
654  AliRun* alirun = dynamic_cast<AliRun*>(fGAFile->Get(fgkGAliceName));
655  if (alirun == 0x0)
656   {
657     AliError(Form("Can not find gAlice in file %s",fGAFile->GetName()));
658     return 2;
659   }
660  alirun->SetRunLoader(this);
661  if (gAlice)
662   {
663     AliWarning(Form("gAlice already exists. Putting retrived object in folder named %s",
664                     GetEventFolder()->GetName()));
665   }
666  else
667   {
668     gAlice = alirun;
669   }
670  SetDetectorAddresses();//calls SetTreeAddress for all detectors
671  return 0; 
672 }
673 /**************************************************************************/
674
675 Int_t AliRunLoader::LoadHeader()
676 {
677 //loads treeE and reads header object for current event
678  if (TreeE())
679   {
680      AliWarning("Header is already loaded. Use ReloadHeader to force reload. Nothing done");
681      return 0;
682   }
683  
684  if (GetEventFolder() == 0x0)
685   {
686     AliError("Event folder not specified yet");
687     return 1;
688   }
689
690  if (fGAFile == 0x0)
691   {
692     AliError("Session not opened. Use AliRunLoader::Open");
693     return 2;
694   }
695  
696  if (fGAFile->IsOpen() == kFALSE)
697   {
698     AliError("Session not opened. Use AliRunLoader::Open");
699     return 2;
700   }
701
702  TTree* tree = dynamic_cast<TTree*>(fGAFile->Get(fgkHeaderContainerName));
703  if (tree == 0x0)
704   {
705     AliError(Form("Can not find header tree named %s in file %s",
706                   fgkHeaderContainerName.Data(),fGAFile->GetName()));
707     return 2;
708   }
709
710  if (tree == TreeE()) return 0;
711
712  CleanHeader();
713  GetEventFolder()->Add(tree);
714  MakeHeader();//creates header object and connects to tree
715  return 0; 
716
717 }
718 /**************************************************************************/
719
720 Int_t AliRunLoader::LoadTrigger(Option_t* option)
721 {
722    //Load treeCT
723
724    if( TreeCT() ) {
725       AliWarning("Trigger is already loaded. Nothing done");
726       return 0;
727    }
728  
729    if( GetEventFolder() == 0x0 ) {
730       AliError("Event folder not specified yet");
731       return 1;
732    }
733    // get the CTP Trigger output file and tree
734   char* tmp = gSystem->ConcatFileName( fUnixDirName.Data(),
735                                       fgkDefaultTriggerFileName.Data() );
736   TString trgfile(tmp);
737   delete[] tmp;
738   
739    TFile* file = gROOT->GetFile( trgfile );
740    if( !file ) {
741       file = TFile::Open( trgfile, option ) ;
742       if (!file || file->IsOpen() == kFALSE ) {
743          AliError( Form( "Can not open trigger file %s", trgfile.Data() ) );
744          return 2;
745       }
746    }
747    file->cd();
748
749    TTree* tree = dynamic_cast<TTree*>(file->Get( fgkTriggerContainerName ));
750    if( !tree ) {
751       AliError( Form( "Can not find trigger tree named %s in file %s",
752                       fgkTriggerContainerName.Data(), file->GetName() ) );
753       return 2;
754    }
755
756    CleanTrigger();
757
758    fCTrigger = dynamic_cast<AliCentralTrigger*>(file->Get( "AliCentralTrigger" ));
759    GetEventFolder()->Add( tree );
760    MakeTrigger();
761
762    return 0;
763 }
764
765 /**************************************************************************/
766
767 Int_t AliRunLoader::LoadKinematics(Option_t* option)
768 {
769 //Loads the kinematics 
770  Int_t retval = fKineDataLoader->GetBaseLoader(0)->Load(option);
771  if (retval)
772   {
773     AliError("Error occured while loading kinamatics tree.");
774     return retval;
775   }
776  if (fStack) 
777   {
778       fStack->ConnectTree(TreeK());
779       retval = fStack->GetEvent();
780     if ( retval == kFALSE)
781      {
782        AliError("Error occured while loading kinamatics tree.");
783        return retval;
784      }
785     
786   }
787  return 0;
788 }
789 /**************************************************************************/
790
791 Int_t AliRunLoader::OpenDataFile(const TString& filename,TFile*& file,TDirectory*& dir,Option_t* opt,Int_t cl)
792 {
793 //Opens File with kinematics
794  if (file)
795   {
796     if (file->IsOpen() == kFALSE)
797      {//pointer is not null but file is not opened
798        AliWarning("Pointer to file is not null, but file is not opened");//risky any way
799        delete file;
800        file = 0x0; //proceed with opening procedure
801      }
802     else
803      { 
804        AliWarning(Form("File  %s already opened",filename.Data()));
805        return 0;
806      }
807   }
808 //try to find if that file is opened somewere else
809  file = (TFile *)( gROOT->GetListOfFiles()->FindObject(filename) );
810  if (file)
811   {
812    if(file->IsOpen() == kTRUE)
813     {
814      AliWarning(Form("File %s already opened by sombody else.",file->GetName()));
815      return 0;
816     }
817   }
818
819  file = TFile::Open(filename,opt);
820  if (file == 0x0)
821   {//file is null
822     AliError(Form("Can not open file %s",filename.Data()));
823     return 1;
824   }
825  if (file->IsOpen() == kFALSE)
826   {//file is not opened
827     AliError(Form("Can not open file %s",filename.Data()));
828    return 1;
829   }
830   
831  file->SetCompressionLevel(cl);
832  
833  dir = AliLoader::ChangeDir(file,fCurrentEvent);
834  if (dir == 0x0)
835   {
836     AliError(Form("Can not change to root directory in file %s",filename.Data()));
837     return 3;
838   }
839  return 0; 
840 }
841 /**************************************************************************/
842
843 TTree* AliRunLoader::TreeE() const
844 {
845  //returns the tree from folder; shortcut method
846  if (AliDebugLevel() > 10) fEventFolder->ls();
847  TObject *obj = fEventFolder->FindObject(fgkHeaderContainerName);
848  return (obj)?dynamic_cast<TTree*>(obj):0x0;
849 }
850 /**************************************************************************/
851
852 TTree* AliRunLoader::TreeCT() const
853 {
854  //returns the tree from folder; shortcut method
855    if (AliDebugLevel() > 10) fEventFolder->ls();
856    TObject *obj = fEventFolder->FindObject(fgkTriggerContainerName);
857    return (obj)?dynamic_cast<TTree*>(obj):0x0;
858 }
859 /**************************************************************************/
860
861 AliHeader* AliRunLoader::GetHeader() const
862 {
863 //returns pointer header object
864  return fHeader;
865 }
866 /**************************************************************************/
867
868 AliCentralTrigger* AliRunLoader::GetTrigger() const
869 {
870 //returns pointer trigger object
871    return fCTrigger;
872 }
873
874 /**************************************************************************/
875  
876 TTree* AliRunLoader::TreeK() const
877 {
878  //returns the tree from folder; shortcut method
879  TObject *obj = GetEventFolder()->FindObject(fgkKineContainerName);
880  return (obj)?dynamic_cast<TTree*>(obj):0x0;
881 }
882 /**************************************************************************/
883
884 TTree* AliRunLoader::TreeTR() const
885 {
886  //returns the tree from folder; shortcut method
887  TObject* obj = GetEventFolder()->FindObject(fgkTrackRefsContainerName);
888  return (obj)?dynamic_cast<TTree*>(obj):0x0;
889 }
890 /**************************************************************************/
891
892 AliRun* AliRunLoader::GetAliRun() const
893 {
894 //returns AliRun which sits in the folder
895  if (fEventFolder == 0x0) return 0x0;
896  TObject *obj = fEventFolder->FindObject(fgkGAliceName);
897  return (obj)?dynamic_cast<AliRun*>(obj):0x0;
898 }
899 /**************************************************************************/
900
901 Int_t AliRunLoader::WriteHeader(Option_t* opt)
902 {
903 //writes treeE
904   AliDebug(1, "WRITING HEADER");
905   
906   TTree* tree = TreeE();
907   if ( tree == 0x0)
908    {
909      AliWarning("Can not find Header Tree in Folder");
910      return 0;
911    } 
912   if (fGAFile->IsWritable() == kFALSE)
913    {
914      AliError(Form("File %s is not writable",fGAFile->GetName()));
915      return 1;
916    }
917
918   TObject* obj = fGAFile->Get(fgkHeaderContainerName);
919   if (obj)
920    { //if they exist, see if option OVERWRITE is used
921      TString tmp(opt);
922      if(tmp.Contains("OVERWRITE",TString::kIgnoreCase) == 0)
923       {//if it is not used -  give an error message and return an error code
924         AliError("Tree already exisists. Use option \"OVERWRITE\" to overwrite previous data");
925         return 3;
926       }
927    }
928   fGAFile->cd();
929   tree->SetDirectory(fGAFile);
930   tree->Write(0,TObject::kOverwrite);
931
932   AliDebug(1, "WRITTEN\n\n");
933   
934   return 0;
935 }
936
937 /**************************************************************************/
938
939 Int_t AliRunLoader::WriteTrigger(Option_t* opt)
940 {
941    //writes TreeCT
942    AliDebug( 1, "WRITING TRIGGER" );
943   
944    TTree* tree = TreeCT();
945    if ( tree == 0x0) {
946       AliWarning("Can not find Trigger Tree in Folder");
947       return 0;
948    }
949
950    TFile* file = gROOT->GetFile( gSystem->ConcatFileName( fUnixDirName.Data(), fgkDefaultTriggerFileName.Data() ) ) ;
951    if( !file || !file->IsOpen() ) {
952       AliError( "can't write Trigger, file is not open" );
953       return kFALSE;
954    }
955
956    TObject* obj = file->Get( fgkTriggerContainerName );
957    if( obj ) { //if they exist, see if option OVERWRITE is used
958       TString tmp(opt);
959       if( tmp.Contains( "OVERWRITE", TString::kIgnoreCase ) == 0) {
960          //if it is not used -  give an error message and return an error code
961          AliError( "Tree already exisists. Use option \"OVERWRITE\" to overwrite previous data" );
962          return 3;
963       }
964    }
965    file->cd();
966    fCTrigger->Write( 0, TObject::kOverwrite );
967    tree->Write( 0, TObject::kOverwrite );
968    file->Flush();
969
970    AliDebug(1, "WRITTEN\n\n");
971   
972    return 0;
973 }
974 /**************************************************************************/
975
976 Int_t AliRunLoader::WriteAliRun(Option_t* /*opt*/)
977 {
978 //writes AliRun object to the file
979   fGAFile->cd();
980   if (GetAliRun()) GetAliRun()->Write();
981   return 0;
982 }
983 /**************************************************************************/
984
985 Int_t AliRunLoader::WriteKinematics(Option_t* opt)
986 {
987 //writes Kinematics
988   return fKineDataLoader->GetBaseLoader(0)->WriteData(opt);
989 }
990 /**************************************************************************/
991 Int_t AliRunLoader::WriteTrackRefs(Option_t* opt)
992 {
993 //writes Track References tree
994   return fTrackRefsDataLoader->GetBaseLoader(0)->WriteData(opt);
995 }
996 /**************************************************************************/
997
998 Int_t AliRunLoader::WriteHits(Option_t* opt)
999 {
1000 //Calls WriteHits for all loaders
1001   Int_t res;
1002   Int_t result = 0;
1003   TIter next(fLoaders);
1004   AliLoader *loader;
1005   while((loader = (AliLoader*)next()))
1006    {
1007      res = loader->WriteHits(opt);
1008      if (res)
1009       {
1010         AliError(Form("Failed to write hits for %s (%d)",loader->GetDetectorName().Data(),res));
1011         result = 1;
1012       }
1013    }
1014   return result;
1015 }
1016 /**************************************************************************/
1017
1018 Int_t AliRunLoader::WriteSDigits(Option_t* opt)
1019 {
1020 //Calls WriteSDigits for all loaders
1021   Int_t res;
1022   Int_t result = 0;
1023   TIter next(fLoaders);
1024   AliLoader *loader;
1025   while((loader = (AliLoader*)next()))
1026    {
1027      res = loader->WriteSDigits(opt);
1028      if (res)
1029       {
1030         AliError(Form("Failed to write summable digits for %s.",loader->GetDetectorName().Data()));
1031         result = 1;
1032       }
1033    }
1034   return result;
1035 }
1036 /**************************************************************************/
1037
1038 Int_t AliRunLoader::WriteDigits(Option_t* opt)
1039 {
1040 //Calls WriteDigits for all loaders
1041   Int_t res;
1042   Int_t result = 0;
1043   TIter next(fLoaders);
1044   AliLoader *loader;
1045   while((loader = (AliLoader*)next()))
1046    { 
1047      res = loader->WriteDigits(opt);
1048      if (res)
1049       {
1050         AliError(Form("Failed to write digits for %s.",loader->GetDetectorName().Data()));
1051         result = 1;
1052       }
1053    }
1054   return result;
1055 }
1056 /**************************************************************************/
1057
1058 Int_t AliRunLoader::WriteRecPoints(Option_t* opt)
1059 {
1060 //Calls WriteRecPoints for all loaders
1061   Int_t res;
1062   Int_t result = 0;
1063   TIter next(fLoaders);
1064   AliLoader *loader;
1065   while((loader = (AliLoader*)next()))
1066    {
1067      res = loader->WriteRecPoints(opt);
1068      if (res)
1069       {
1070         AliError(Form("Failed to write Reconstructed Points for %s.",
1071                       loader->GetDetectorName().Data()));
1072         result = 1;
1073       }
1074    }
1075   return result;
1076 }
1077 /**************************************************************************/
1078
1079 Int_t AliRunLoader::WriteTracks(Option_t* opt)
1080 {
1081 //Calls WriteTracks for all loaders
1082   Int_t res;
1083   Int_t result = 0;
1084   TIter next(fLoaders);
1085   AliLoader *loader;
1086   while((loader = (AliLoader*)next()))
1087    {
1088      res = loader->WriteTracks(opt);
1089      if (res)
1090       {
1091         AliError(Form("Failed to write Tracks for %s.",
1092                       loader->GetDetectorName().Data()));
1093         result = 1;
1094       }
1095    }
1096   return result;
1097 }
1098 /**************************************************************************/
1099
1100 Int_t AliRunLoader::WriteRunLoader(Option_t* /*opt*/)
1101 {
1102 //Writes itself to the file
1103   CdGAFile();
1104   this->Write(0,TObject::kOverwrite);
1105   return 0;
1106 }
1107 /**************************************************************************/
1108
1109 Int_t AliRunLoader::SetEventFolderName(const TString& name)
1110 {  
1111 //sets top folder name for this run; of alread
1112   if (name.IsNull())
1113    {
1114      AliError("Name is empty");
1115      return 1;
1116    }
1117   
1118   //check if such a folder already exists - try to find it in alice top folder
1119   TObject* obj = AliConfig::Instance()->GetTopFolder()->FindObject(name);
1120   if(obj)
1121    {
1122      TFolder* fold = dynamic_cast<TFolder*>(obj);
1123      if (fold == 0x0)
1124       {
1125        AliError("Such a obejct already exists in top alice folder and it is not a folder.");
1126        return 2;
1127       }
1128      //folder which was found is our folder
1129      if (fEventFolder == fold)
1130       {
1131        return 0;
1132       }
1133      else
1134       {
1135        AliError("Such a folder already exists in top alice folder. Can not mount.");
1136        return 2;
1137       }
1138    }
1139
1140   //event is alredy connected, just change name of the folder
1141   if (fEventFolder) 
1142    {
1143      fEventFolder->SetName(name);
1144      return 0;
1145    }
1146
1147   if (fKineDataLoader == 0x0)
1148     fKineDataLoader = new AliDataLoader(fgkDefaultKineFileName,fgkKineContainerName,"Kinematics");
1149
1150   if ( fTrackRefsDataLoader == 0x0)
1151     fTrackRefsDataLoader = new AliDataLoader(fgkDefaultTrackRefsFileName,fgkTrackRefsContainerName,"Track References");
1152    
1153   //build the event folder structure
1154   AliDebug(1, Form("Creating new event folder named %s",name.Data()));
1155   fEventFolder = AliConfig::Instance()->BuildEventFolder(name,"Event Folder");
1156   fEventFolder->Add(this);//put myself to the folder to accessible for all
1157   
1158   TIter next(fLoaders);
1159   AliLoader *loader;
1160   while((loader = (AliLoader*)next()))
1161    {
1162      loader->Register(fEventFolder);//build folder structure for this detector
1163    }
1164   
1165   fKineDataLoader->SetEventFolder(GetEventFolder());
1166   fTrackRefsDataLoader->SetEventFolder(GetEventFolder());
1167   fKineDataLoader->SetFolder(GetEventFolder());
1168   fTrackRefsDataLoader->SetFolder(GetEventFolder());
1169   
1170   fEventFolder->SetOwner();
1171   return 0;
1172 }
1173 /**************************************************************************/
1174
1175 void AliRunLoader::AddLoader(AliLoader* loader)
1176  {
1177  //Adds the Loader for given detector 
1178   if (loader == 0x0) //if null shout and exit
1179    {
1180      AliError("Parameter is NULL");
1181      return;
1182    }
1183   loader->SetDirName(fUnixDirName);
1184   if (fEventFolder) loader->SetEventFolder(fEventFolder); //if event folder is already defined, 
1185                                                           //pass information to the Loader
1186   fLoaders->Add(loader);//add the Loader to the array
1187  }
1188 /**************************************************************************/
1189
1190 void AliRunLoader::AddLoader(AliDetector* det)
1191  {
1192 //Asks module (detector) ro make a Loader and stores in the array
1193    if (det == 0x0) return;
1194    AliLoader* get = det->GetLoader();//try to get loader
1195    if (get == 0x0)  get = det->MakeLoader(fEventFolder->GetName());//if did not obtain, ask to make it
1196
1197    if (get) 
1198     {
1199       AliDebug(1, Form("Detector: %s   Loader : %s",det->GetName(),get->GetName()));
1200       AddLoader(get);
1201     }
1202  }
1203
1204 /**************************************************************************/
1205
1206 AliLoader* AliRunLoader::GetLoader(const char* detname) const
1207 {
1208 //returns loader for given detector
1209 //note that naming convention is TPCLoader not just TPC
1210   return (AliLoader*)fLoaders->FindObject(detname);
1211 }
1212
1213 /**************************************************************************/
1214
1215 AliLoader* AliRunLoader::GetLoader(AliDetector* det) const
1216 {
1217 //get loader for detector det
1218  if(det == 0x0) return 0x0;
1219  TString getname(det->GetName());
1220  getname+="Loader";
1221  AliDebug(1, Form(" Loader name is %s",getname.Data()));
1222  return GetLoader(getname);
1223 }
1224
1225 /**************************************************************************/
1226
1227 void AliRunLoader::CleanFolders()
1228 {
1229 //  fEventFolder->Add(this);//put myself to the folder to accessible for all
1230
1231   CleanDetectors();
1232   CleanHeader();
1233   CleanKinematics();
1234   CleanTrigger();
1235 }
1236 /**************************************************************************/
1237
1238 void AliRunLoader::CleanDetectors()
1239 {
1240 //Calls CleanFolders for all detectors
1241   TIter next(fLoaders);
1242   AliLoader *loader;
1243   while((loader = (AliLoader*)next())) 
1244    {
1245      loader->CleanFolders();
1246    }
1247 }
1248 /**************************************************************************/
1249
1250 void AliRunLoader::RemoveEventFolder()
1251 {
1252 //remove all the tree of event 
1253 //all the stuff changing EbE stays untached (PDGDB, tasks, etc.)
1254
1255  if (fEventFolder == 0x0) return;
1256  fEventFolder->SetOwner(kFALSE);//don't we want to deleted while removing the folder that we are sitting in
1257  fEventFolder->Remove(this);//remove us drom folder
1258  
1259  AliConfig::Instance()->GetTopFolder()->SetOwner(); //brings ownership back for fEventFolder since it sits in top folder
1260  AliConfig::Instance()->GetTopFolder()->Remove(fEventFolder); //remove the event tree
1261  delete fEventFolder;
1262 }
1263 /**************************************************************************/
1264
1265 void AliRunLoader::SetGAliceFile(TFile* gafile)
1266 {
1267 //sets pointer to galice.root file
1268  fGAFile = gafile;
1269 }
1270
1271 /**************************************************************************/
1272
1273 Int_t AliRunLoader::LoadHits(Option_t* detectors,Option_t* opt)
1274 {
1275 //LoadHits in selected detectors i.e. detectors="ITS TPC TRD" or "all"
1276
1277   AliDebug(1, "Loading Hits");
1278   TObjArray* loaders;
1279   TObjArray arr;
1280
1281   const char* oAll = strstr(detectors,"all");
1282   if (oAll)
1283    {
1284      AliDebug(1, "Option is All");
1285      loaders = fLoaders;
1286    }
1287   else
1288    {
1289      GetListOfDetectors(detectors,arr);//this method looks for all Loaders corresponding to names (many) specified in detectors option
1290      loaders = &arr;//get the pointer array
1291    }   
1292
1293   AliDebug(1, Form("For detectors. Number of detectors chosen for loading %d",loaders->GetEntries()));
1294   
1295   TIter next(loaders);
1296   AliLoader *loader;
1297   while((loader = (AliLoader*)next())) 
1298    {
1299     AliDebug(1, Form("    Calling LoadHits(%s) for %s",opt,loader->GetName()));
1300     loader->LoadHits(opt);
1301    }
1302   AliDebug(1, "Done");
1303   return 0;
1304
1305
1306 /**************************************************************************/
1307
1308 Int_t AliRunLoader::LoadSDigits(Option_t* detectors,Option_t* opt)
1309 {
1310 //LoadHits in selected detectors i.e. detectors="ITS TPC TRD" or "all"
1311
1312   TObjArray* loaders;
1313   TObjArray arr;
1314
1315   const char* oAll = strstr(detectors,"all");
1316   if (oAll)
1317    {
1318      loaders = fLoaders;
1319    }
1320   else
1321    {
1322      GetListOfDetectors(detectors,arr);//this method looks for all Loaders corresponding to names (many) specified in detectors option
1323      loaders = &arr;//get the pointer to array
1324    }   
1325
1326   TIter next(loaders);
1327   AliLoader *loader;
1328   while((loader = (AliLoader*)next())) 
1329    {
1330     loader->LoadSDigits(opt);
1331    }
1332   return 0;
1333
1334
1335 /**************************************************************************/
1336
1337 Int_t AliRunLoader::LoadDigits(Option_t* detectors,Option_t* opt)
1338 {
1339 //LoadHits in selected detectors i.e. detectors="ITS TPC TRD" or "all"
1340
1341   TObjArray* loaders;
1342   TObjArray arr;
1343
1344   const char* oAll = strstr(detectors,"all");
1345   if (oAll)
1346    {
1347      loaders = fLoaders;
1348    }
1349   else
1350    {
1351      GetListOfDetectors(detectors,arr);//this method looks for all Loaders corresponding to names (many) specified in detectors option
1352      loaders = &arr;//get the pointer array
1353    }   
1354
1355   TIter next(loaders);
1356   AliLoader *loader;
1357   while((loader = (AliLoader*)next())) 
1358    {
1359     loader->LoadDigits(opt);
1360    }
1361   return 0;
1362
1363 /**************************************************************************/
1364
1365 Int_t AliRunLoader::LoadRecPoints(Option_t* detectors,Option_t* opt)
1366 {
1367 //LoadHits in selected detectors i.e. detectors="ITS TPC TRD" or "all"
1368
1369   TObjArray* loaders;
1370   TObjArray arr;
1371
1372   const char* oAll = strstr(detectors,"all");
1373   if (oAll)
1374    {
1375      loaders = fLoaders;
1376    }
1377   else
1378    {
1379      GetListOfDetectors(detectors,arr);//this method looks for all Loaders corresponding to names (many) specified in detectors option
1380      loaders = &arr;//get the pointer array
1381    }   
1382
1383   TIter next(loaders);
1384   AliLoader *loader;
1385   while((loader = (AliLoader*)next())) 
1386    {
1387     loader->LoadRecPoints(opt);
1388    }
1389   return 0;
1390
1391 /**************************************************************************/
1392
1393 Int_t AliRunLoader::LoadRecParticles(Option_t* detectors,Option_t* opt)
1394 {
1395 //LoadHits in selected detectors i.e. detectors="ITS TPC TRD" or "all"
1396
1397   TObjArray* loaders;
1398   TObjArray arr;
1399
1400   const char* oAll = strstr(detectors,"all");
1401   if (oAll)
1402    {
1403      loaders = fLoaders;
1404    }
1405   else
1406    {
1407      GetListOfDetectors(detectors,arr);//this method looks for all Loaders corresponding to names (many) specified in detectors option
1408      loaders = &arr;//get the pointer array
1409    }   
1410
1411   TIter next(loaders);
1412   AliLoader *loader;
1413   while((loader = (AliLoader*)next())) 
1414    {
1415     loader->LoadRecParticles(opt);
1416    }
1417   return 0;
1418
1419 /**************************************************************************/
1420
1421 Int_t AliRunLoader::LoadTracks(Option_t* detectors,Option_t* opt)
1422 {
1423 //LoadHits in selected detectors i.e. detectors="ITS TPC TRD" or "all"
1424
1425   TObjArray* loaders;
1426   TObjArray arr;
1427
1428   const char* oAll = strstr(detectors,"all");
1429   if (oAll)
1430    {
1431      loaders = fLoaders;
1432    }
1433   else
1434    {
1435      GetListOfDetectors(detectors,arr);//this method looks for all Loaders corresponding to names (many) specified in detectors option
1436      loaders = &arr;//get the pointer array
1437    }   
1438
1439   TIter next(loaders);
1440   AliLoader *loader;
1441   while((loader = (AliLoader*)next())) 
1442    {
1443     loader->LoadTracks(opt);
1444    }
1445   return 0;
1446
1447 /**************************************************************************/
1448
1449 void AliRunLoader::UnloadHits(Option_t* detectors)
1450 {
1451   //unloads hits for detectors specified in parameter
1452   TObjArray* loaders;
1453   TObjArray arr;
1454
1455   const char* oAll = strstr(detectors,"all");
1456   if (oAll)
1457    {
1458      loaders = fLoaders;
1459    }
1460   else
1461    {
1462      GetListOfDetectors(detectors,arr);//this method looks for all Loaders corresponding to names (many) specified in detectors option
1463      loaders = &arr;//get the pointer to array
1464    }   
1465
1466   TIter next(loaders);
1467   AliLoader *loader;
1468   while((loader = (AliLoader*)next())) 
1469    {
1470     loader->UnloadHits();
1471    }
1472 }
1473 /**************************************************************************/
1474
1475 void AliRunLoader::UnloadSDigits(Option_t* detectors)
1476 {
1477   //unloads SDigits for detectors specified in parameter
1478   TObjArray* loaders;
1479   TObjArray arr;
1480
1481   const char* oAll = strstr(detectors,"all");
1482   if (oAll)
1483    {
1484      loaders = fLoaders;
1485    }
1486   else
1487    {
1488      GetListOfDetectors(detectors,arr);//this method looks for all Loaders corresponding to names (many) specified in detectors option
1489      loaders = &arr;//get the pointer to array
1490    }   
1491
1492   TIter next(loaders);
1493   AliLoader *loader;
1494   while((loader = (AliLoader*)next())) 
1495    {
1496     loader->UnloadSDigits();
1497    }
1498 }
1499 /**************************************************************************/
1500
1501 void AliRunLoader::UnloadDigits(Option_t* detectors)
1502 {
1503   //unloads Digits for detectors specified in parameter
1504   TObjArray* loaders;
1505   TObjArray arr;
1506
1507   const char* oAll = strstr(detectors,"all");
1508   if (oAll)
1509    {
1510      loaders = fLoaders;
1511    }
1512   else
1513    {
1514      GetListOfDetectors(detectors,arr);//this method looks for all Loaders corresponding to names (many) specified in detectors option
1515      loaders = &arr;//get the pointer to array
1516    }   
1517
1518   TIter next(loaders);
1519   AliLoader *loader;
1520   while((loader = (AliLoader*)next())) 
1521    {
1522     loader->UnloadDigits();
1523    }
1524 }
1525 /**************************************************************************/
1526
1527 void AliRunLoader::UnloadRecPoints(Option_t* detectors)
1528 {
1529   //unloads RecPoints for detectors specified in parameter
1530   TObjArray* loaders;
1531   TObjArray arr;
1532
1533   const char* oAll = strstr(detectors,"all");
1534   if (oAll)
1535    {
1536      loaders = fLoaders;
1537    }
1538   else
1539    {
1540      GetListOfDetectors(detectors,arr);//this method looks for all Loaders corresponding to names (many) specified in detectors option
1541      loaders = &arr;//get the pointer to array
1542    }   
1543
1544   TIter next(loaders);
1545   AliLoader *loader;
1546   while((loader = (AliLoader*)next())) 
1547    {
1548     loader->UnloadRecPoints();
1549    }
1550 }
1551 /**************************************************************************/
1552
1553 void AliRunLoader::UnloadAll(Option_t* detectors)
1554 {
1555   //calls UnloadAll for detectors names specified in parameter
1556   // option "all" passed can be passed
1557   TObjArray* loaders;
1558   TObjArray arr;
1559
1560   const char* oAll = strstr(detectors,"all");
1561   if (oAll)
1562    {
1563      loaders = fLoaders;
1564    }
1565   else
1566    {
1567      GetListOfDetectors(detectors,arr);//this method looks for all Loaders corresponding to names (many) specified in detectors option
1568      loaders = &arr;//get the pointer to array
1569    }   
1570
1571   TIter next(loaders);
1572   AliLoader *loader;
1573   while((loader = (AliLoader*)next())) 
1574    {
1575     loader->UnloadAll();
1576    }
1577 }
1578 /**************************************************************************/
1579
1580 void AliRunLoader::UnloadTracks(Option_t* detectors)
1581 {
1582   //unloads Tracks for detectors specified in parameter
1583   TObjArray* loaders;
1584   TObjArray arr;
1585
1586   const char* oAll = strstr(detectors,"all");
1587   if (oAll)
1588    {
1589      loaders = fLoaders;
1590    }
1591   else
1592    {
1593      GetListOfDetectors(detectors,arr);//this method looks for all Loaders corresponding to names (many) specified in detectors option
1594      loaders = &arr;//get the pointer to array
1595    }   
1596
1597   TIter next(loaders);
1598   AliLoader *loader;
1599   while((loader = (AliLoader*)next())) 
1600    {
1601     loader->UnloadTracks();
1602    }
1603 }
1604 /**************************************************************************/
1605
1606 void AliRunLoader::UnloadRecParticles(Option_t* detectors)
1607 {
1608   //unloads Particles for detectors specified in parameter
1609   TObjArray* loaders;
1610   TObjArray arr;
1611
1612   const char* oAll = strstr(detectors,"all");
1613   if (oAll)
1614    {
1615      loaders = fLoaders;
1616    }
1617   else
1618    {
1619      GetListOfDetectors(detectors,arr);//this method looks for all Loaders corresponding to names (many) specified in detectors option
1620      loaders = &arr;//get the pointer to array
1621    }   
1622
1623   TIter next(loaders);
1624   AliLoader *loader;
1625   while((loader = (AliLoader*)next())) 
1626    {
1627     loader->UnloadRecParticles();
1628    }
1629 }
1630 /**************************************************************************/
1631
1632 AliRunLoader* AliRunLoader::GetRunLoader(const char* eventfoldername)
1633 {
1634 //returns RunLoader from folder named eventfoldername
1635   TFolder* evfold= dynamic_cast<TFolder*>(AliConfig::Instance()->GetTopFolder()->FindObject(eventfoldername));
1636   if (evfold == 0x0)
1637    {
1638      return 0x0;
1639    }
1640   AliRunLoader* runget = dynamic_cast<AliRunLoader*>(evfold->FindObject(AliRunLoader::fgkRunLoaderName));
1641   return runget;
1642   
1643 }
1644 /**************************************************************************/
1645
1646 AliLoader* AliRunLoader::GetDetectorLoader(const char* detname, const char* eventfoldername)
1647 {
1648 //get the loader of the detector with the given name from the global
1649 //run loader object
1650   AliRunLoader* runLoader = GetRunLoader(eventfoldername);
1651   if (!runLoader) {
1652     AliErrorClass("No run loader found");
1653     return NULL;
1654   }
1655   return runLoader->GetDetectorLoader(detname);
1656 }
1657 /**************************************************************************/
1658
1659 AliLoader* AliRunLoader::GetDetectorLoader(const char* detname)
1660 {
1661 //get the loader of the detector with the given name from the global
1662 //run loader object
1663   
1664   char loadername[256];
1665   sprintf(loadername, "%sLoader", detname);
1666   AliLoader* loader = GetLoader(loadername);
1667   if (!loader) {
1668     AliError(Form("No loader for %s found", detname));
1669     return NULL;
1670   }
1671   return loader;
1672 }
1673 /**************************************************************************/
1674
1675 TTree* AliRunLoader::GetTreeH(const char* detname, Bool_t maketree, const char* eventfoldername)
1676 {
1677 //get the tree with hits of the detector with the given name
1678 //if maketree is true and the tree does not exist, the tree is created
1679   AliLoader* loader = GetDetectorLoader(detname,eventfoldername);
1680   if (!loader) return NULL;
1681   if (!loader->TreeH() && maketree) loader->MakeTree("H");
1682   return loader->TreeH();
1683 }
1684
1685 /**************************************************************************/
1686
1687 TTree* AliRunLoader::GetTreeH(const char* detname, Bool_t maketree)
1688 {
1689 //get the tree with hits of the detector with the given name
1690 //if maketree is true and the tree does not exist, the tree is created
1691   AliLoader* loader = GetDetectorLoader(detname);
1692   if (!loader) return NULL;
1693   if (!loader->TreeH() && maketree) loader->MakeTree("H");
1694   return loader->TreeH();
1695 }
1696 /**************************************************************************/
1697
1698 TTree* AliRunLoader::GetTreeS(const char* detname, Bool_t maketree,const char* eventfoldername)
1699 {
1700 //get the tree with summable digits of the detector with the given name
1701 //if maketree is true and the tree does not exist, the tree is created
1702   AliLoader* loader = GetDetectorLoader(detname,eventfoldername);
1703   if (!loader) return NULL;
1704   if (!loader->TreeS() && maketree) loader->MakeTree("S");
1705   return loader->TreeS();
1706 }
1707 /**************************************************************************/
1708
1709 TTree* AliRunLoader::GetTreeS(const char* detname, Bool_t maketree)
1710 {
1711 //get the tree with summable digits of the detector with the given name
1712 //if maketree is true and the tree does not exist, the tree is created
1713   AliLoader* loader = GetDetectorLoader(detname);
1714   if (!loader) return NULL;
1715   if (!loader->TreeS() && maketree) loader->MakeTree("S");
1716   return loader->TreeS();
1717 }
1718 /**************************************************************************/
1719
1720 TTree* AliRunLoader::GetTreeD(const char* detname, Bool_t maketree,const char* eventfoldername)
1721 {
1722 //get the tree with digits of the detector with the given name
1723 //if maketree is true and the tree does not exist, the tree is created
1724   AliLoader* loader = GetDetectorLoader(detname,eventfoldername);
1725   if (!loader) return NULL;
1726   if (!loader->TreeD() && maketree) loader->MakeTree("D");
1727   return loader->TreeD();
1728 }
1729 /**************************************************************************/
1730
1731 TTree* AliRunLoader::GetTreeD(const char* detname, Bool_t maketree)
1732 {
1733 //get the tree with digits of the detector with the given name
1734 //if maketree is true and the tree does not exist, the tree is created
1735   AliLoader* loader = GetDetectorLoader(detname);
1736   if (!loader) return NULL;
1737   if (!loader->TreeD() && maketree) loader->MakeTree("D");
1738   return loader->TreeD();
1739 }
1740 /**************************************************************************/
1741 TTree* AliRunLoader::GetTreeR(const char* detname, Bool_t maketree,const char* eventfoldername)
1742 {
1743 //get the tree with clusters of the detector with the given name
1744 //if maketree is true and the tree does not exist, the tree is created
1745   AliLoader* loader = GetDetectorLoader(detname,eventfoldername);
1746   if (!loader) return NULL;
1747   if (!loader->TreeR() && maketree) loader->MakeTree("R");
1748   return loader->TreeR();
1749 }
1750 /**************************************************************************/
1751
1752 TTree* AliRunLoader::GetTreeR(const char* detname, Bool_t maketree)
1753 {
1754 //get the tree with clusters of the detector with the given name
1755 //if maketree is true and the tree does not exist, the tree is created
1756   AliLoader* loader = GetDetectorLoader(detname);
1757   if (!loader) return NULL;
1758   if (!loader->TreeR() && maketree) loader->MakeTree("R");
1759   return loader->TreeR();
1760 }
1761 /**************************************************************************/
1762
1763 TTree* AliRunLoader::GetTreeT(const char* detname, Bool_t maketree,const char* eventfoldername)
1764 {
1765 //get the tree with tracks of the detector with the given name
1766 //if maketree is true and the tree does not exist, the tree is created
1767   AliLoader* loader = GetDetectorLoader(detname,eventfoldername);
1768   if (!loader) return NULL;
1769   if (!loader->TreeT() && maketree) loader->MakeTree("T");
1770   return loader->TreeT();
1771 }
1772 /**************************************************************************/
1773
1774 TTree* AliRunLoader::GetTreeT(const char* detname, Bool_t maketree)
1775 {
1776 //get the tree with tracks of the detector with the given name
1777 //if maketree is true and the tree does not exist, the tree is created
1778   AliLoader* loader = GetDetectorLoader(detname);
1779   if (!loader) return NULL;
1780   if (!loader->TreeT() && maketree) loader->MakeTree("T");
1781   return loader->TreeT();
1782 }
1783 /**************************************************************************/
1784
1785 TTree* AliRunLoader::GetTreeP(const char* detname, Bool_t maketree,const char* eventfoldername)
1786 {
1787 //get the tree with particles of the detector with the given name
1788 //if maketree is true and the tree does not exist, the tree is created
1789   AliLoader* loader = GetDetectorLoader(detname,eventfoldername);
1790   if (!loader) return NULL;
1791   if (!loader->TreeP() && maketree) loader->MakeTree("P");
1792   return loader->TreeP();
1793 }
1794 /**************************************************************************/
1795
1796 TTree* AliRunLoader::GetTreeP(const char* detname, Bool_t maketree)
1797 {
1798 //get the tree with particles of the detector with the given name
1799 //if maketree is true and the tree does not exist, the tree is created
1800   AliLoader* loader = GetDetectorLoader(detname);
1801   if (!loader) return NULL;
1802   if (!loader->TreeP() && maketree) loader->MakeTree("P");
1803   return loader->TreeP();
1804 }
1805
1806 /**************************************************************************/
1807
1808 void AliRunLoader::CdGAFile()
1809 {
1810 //sets gDirectory to galice file
1811 //work around 
1812   if(fGAFile) fGAFile->cd();
1813 }
1814  
1815 /**************************************************************************/
1816
1817 void AliRunLoader::GetListOfDetectors(const char * namelist,TObjArray& pointerarray) const
1818  {
1819 //this method looks for all Loaders corresponding 
1820 //to names (many) specified in namelist i.e. namelist ("ITS TPC TRD")
1821   
1822    char buff[10];
1823    char dets [200];
1824    strcpy(dets,namelist);//compiler cries when char* = const Option_t*;
1825    dets[strlen(dets)+1] = '\n';//set endl at the end of string 
1826    char* pdet = dets;
1827    Int_t tmp;
1828    for(;;)
1829     {
1830       tmp = sscanf(pdet,"%s",buff);//read the string from the input string pdet into buff
1831       if ( (buff[0] == 0) || (tmp == 0) ) break; //if not read
1832      
1833       pdet = strstr(pdet,buff) + strlen(buff);//move the input pointer about number of bytes (letters) read
1834       //I am aware that is a little complicated. I don't know the number of spaces between detector names
1835       //so I read the string, than I find where it starts (strstr) and move the pointer about length of a string
1836       //If there is a better way, please write me (Piotr.Skowronski@cern.ch)
1837       //construct the Loader name
1838       TString getname(buff);
1839       getname+="Loader";
1840       AliLoader* loader = GetLoader(getname);//get the Loader
1841       if (loader)
1842        {
1843         pointerarray.Add(loader);
1844        }
1845       else
1846        {
1847         AliError(Form("Can not find Loader for %s",buff));
1848        }
1849         
1850       buff[0] = 0;
1851     }
1852  }
1853 /*****************************************************************************/ 
1854
1855 void AliRunLoader::Clean(const TString& name)
1856 {
1857 //removes object with given name from event folder and deletes it
1858   if (GetEventFolder() == 0x0) return;
1859   TObject* obj = GetEventFolder()->FindObject(name);
1860   if(obj)
1861    {
1862      AliDebug(1, Form("name=%s, cleaning %s.",GetName(),name.Data()));
1863      GetEventFolder()->Remove(obj);
1864      delete obj;
1865      obj = 0x0;
1866    }
1867 }
1868
1869 /*****************************************************************************/ 
1870
1871 TTask* AliRunLoader::GetRunDigitizer()
1872 {
1873 //returns Run Digitizer from folder
1874
1875  TFolder* topf = AliConfig::Instance()->GetTaskFolder();
1876  TObject* obj = topf->FindObjectAny(AliConfig::Instance()->GetDigitizerTaskName());
1877  return (obj)?dynamic_cast<TTask*>(obj):0x0;
1878 }
1879 /*****************************************************************************/ 
1880
1881 TTask* AliRunLoader::GetRunSDigitizer()
1882 {
1883 //returns SDigitizer Task from folder
1884
1885  TFolder* topf = AliConfig::Instance()->GetTaskFolder();
1886  TObject* obj = topf->FindObjectAny(AliConfig::Instance()->GetSDigitizerTaskName());
1887  return (obj)?dynamic_cast<TTask*>(obj):0x0;
1888 }
1889 /*****************************************************************************/ 
1890
1891 TTask* AliRunLoader::GetRunReconstructioner()
1892 {
1893 //returns Reconstructioner Task from folder
1894  TFolder* topf = AliConfig::Instance()->GetTaskFolder();
1895  TObject* obj = topf->FindObjectAny(AliConfig::Instance()->GetReconstructionerTaskName());
1896  return (obj)?dynamic_cast<TTask*>(obj):0x0;
1897 }
1898 /*****************************************************************************/ 
1899
1900 TTask* AliRunLoader::GetRunTracker()
1901 {
1902 //returns Tracker Task from folder
1903  TFolder* topf = AliConfig::Instance()->GetTaskFolder();
1904  TObject* obj = topf->FindObjectAny(AliConfig::Instance()->GetTrackerTaskName());
1905  return (obj)?dynamic_cast<TTask*>(obj):0x0;
1906 }
1907 /*****************************************************************************/ 
1908
1909 TTask* AliRunLoader::GetRunPIDTask()
1910 {
1911 //returns Tracker Task from folder
1912  TFolder* topf = AliConfig::Instance()->GetTaskFolder();
1913  TObject* obj = topf->FindObjectAny(AliConfig::Instance()->GetPIDTaskName());
1914  return (obj)?dynamic_cast<TTask*>(obj):0x0;
1915 }
1916 /*****************************************************************************/ 
1917
1918 TTask* AliRunLoader::GetRunQATask()
1919 {
1920 //returns Quality Assurance Task from folder
1921  TFolder* topf = AliConfig::Instance()->GetTaskFolder();
1922  if (topf == 0x0)
1923   {
1924     AliErrorClass("Can not get task folder from AliConfig");
1925     return 0x0;
1926   }
1927  TObject* obj = topf->FindObjectAny(AliConfig::Instance()->GetQATaskName());
1928  return (obj)?dynamic_cast<TTask*>(obj):0x0;
1929 }
1930
1931 /*****************************************************************************/ 
1932
1933 void AliRunLoader::SetCompressionLevel(Int_t cl)
1934 {
1935 //Sets Compression Level in all files
1936  if (fGAFile) fGAFile->SetCompressionLevel(cl);
1937  SetKineComprLevel(cl);
1938  SetTrackRefsComprLevel(cl);
1939  TIter next(fLoaders);
1940  AliLoader *loader;
1941  while((loader = (AliLoader*)next()))
1942   {
1943    loader->SetCompressionLevel(cl);
1944   }
1945 }
1946 /**************************************************************************/
1947
1948 void AliRunLoader::SetKineComprLevel(Int_t cl)
1949 {
1950 //Sets comression level in Kine File
1951   fKineDataLoader->SetCompressionLevel(cl);
1952 }
1953 /**************************************************************************/
1954
1955 void AliRunLoader::SetTrackRefsComprLevel(Int_t cl)
1956 {
1957 //Sets comression level in Track Refences File
1958   fTrackRefsDataLoader->SetCompressionLevel(cl);
1959 }
1960 /**************************************************************************/
1961
1962 void AliRunLoader::UnloadHeader()
1963 {
1964  //removes TreeE from folder and deletes it
1965  // as well as fHeader object
1966  CleanHeader();
1967  delete fHeader;
1968  fHeader = 0x0;
1969 }
1970 /**************************************************************************/
1971
1972 void AliRunLoader::UnloadTrigger()
1973 {
1974  //removes TreeCT from folder and deletes it
1975  // as well as fHeader object
1976    CleanTrigger();
1977    delete fCTrigger;
1978    fCTrigger = 0x0;
1979 }
1980
1981 /**************************************************************************/
1982
1983 void AliRunLoader::UnloadKinematics()
1984 {
1985 //Unloads Kinematics
1986  fKineDataLoader->GetBaseLoader(0)->Unload();
1987 }
1988 /**************************************************************************/
1989
1990 void AliRunLoader::UnloadTrackRefs()
1991 {
1992 //Unloads Track Refernces
1993  fTrackRefsDataLoader->GetBaseLoader(0)->Unload();
1994 }
1995 /**************************************************************************/
1996
1997 void AliRunLoader::UnloadgAlice()
1998 {
1999 //Unloads gAlice
2000  if (gAlice == GetAliRun())
2001   {
2002    AliDebug(1, "Set gAlice = 0x0");
2003    gAlice = 0x0;//if gAlice is the same that in folder (to be deleted by the way of folder)
2004   }
2005  AliRun* alirun = GetAliRun();
2006  if (GetEventFolder()) GetEventFolder()->Remove(alirun);
2007  delete alirun;
2008 }
2009 /**************************************************************************/
2010
2011 void  AliRunLoader::MakeTrackRefsContainer()
2012 {
2013 // Makes a tree for Track References
2014   fTrackRefsDataLoader->MakeTree();
2015 }
2016 /**************************************************************************/
2017
2018 Int_t AliRunLoader::LoadTrackRefs(Option_t* option)
2019 {
2020 //Load track references from file (opens file and posts tree to folder)
2021
2022  return fTrackRefsDataLoader->GetBaseLoader(0)->Load(option);
2023 }
2024 /**************************************************************************/
2025
2026 void  AliRunLoader::SetDirName(TString& dirname)
2027 {
2028 //sets directory name 
2029   if (dirname.IsNull()) return;
2030   fUnixDirName = dirname;
2031   fKineDataLoader->SetDirName(dirname);
2032   fTrackRefsDataLoader->SetDirName(dirname);
2033   
2034   TIter next(fLoaders);
2035   AliLoader *loader;
2036   while((loader = (AliLoader*)next()))
2037    {
2038     loader->SetDirName(dirname);
2039    }
2040
2041 }
2042 /*****************************************************************************/ 
2043
2044 Int_t AliRunLoader::GetFileOffset() const
2045 {
2046 //returns the file number that is added to the file name for current event
2047   return Int_t(fCurrentEvent/fNEventsPerFile);
2048 }
2049
2050 /*****************************************************************************/ 
2051 const TString AliRunLoader::SetFileOffset(const TString& fname)
2052 {
2053 //adds the the number to the file name at proper place for current event
2054   Long_t offset = (Long_t)GetFileOffset();
2055   if (offset < 1) return fname;
2056   TString soffset;
2057   soffset += offset;//automatic conversion to string
2058   TString dotroot(".root");
2059   const TString& offfsetdotroot = offset + dotroot;
2060   TString out = fname;
2061   out = out.ReplaceAll(dotroot,offfsetdotroot);
2062   AliDebug(1, Form(" in=%s out=%s",fname.Data(),out.Data()));
2063   return out;
2064 }
2065 /*****************************************************************************/ 
2066
2067 void AliRunLoader::SetDigitsFileNameSuffix(const TString& suffix)
2068 {
2069 //adds the suffix before ".root", 
2070 //e.g. TPC.Digits.root -> TPC.DigitsMerged.root
2071 //made on Jiri Chudoba demand
2072
2073   TIter next(fLoaders);
2074   AliLoader *loader;
2075   while((loader = (AliLoader*)next())) 
2076    {
2077      loader->SetDigitsFileNameSuffix(suffix);
2078    }
2079 }
2080 /*****************************************************************************/ 
2081
2082 TString AliRunLoader::GetFileName() const
2083 {
2084 //returns name of galice file
2085  TString result;
2086  if (fGAFile == 0x0) return result;
2087  result = fGAFile->GetName();
2088  return result;
2089 }
2090 /*****************************************************************************/ 
2091
2092 void AliRunLoader::SetDetectorAddresses()
2093 {
2094  //calls SetTreeAddress for all detectors
2095   if (GetAliRun()==0x0) return;
2096   TIter next(GetAliRun()->Modules());
2097   AliModule* mod;
2098   while((mod = (AliModule*)next())) 
2099    {
2100      AliDetector* det = dynamic_cast<AliDetector*>(mod);
2101      if (det) det->SetTreeAddress();
2102    }
2103 }
2104 /*****************************************************************************/ 
2105
2106 void AliRunLoader::Synchronize()
2107 {
2108   //synchrinizes all writtable files 
2109   TIter next(fLoaders);
2110   AliLoader *loader;
2111   while((loader = (AliLoader*)next()))
2112    {
2113      loader->Synchronize();
2114    }
2115   
2116   fKineDataLoader->Synchronize();
2117   fTrackRefsDataLoader->Synchronize();
2118
2119   TFile* file = gROOT->GetFile( gSystem->ConcatFileName( fUnixDirName.Data(), fgkDefaultTriggerFileName.Data() ) ) ;
2120   if( file ) file->Flush();
2121   
2122   if (fGAFile) fGAFile->Flush();
2123 }
2124 /*****************************************************************************/ 
2125 /*****************************************************************************/