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