]> git.uio.no Git - u/mrichter/AliRoot.git/blob - STEER/AliAODHandler.cxx
M AliTPCcalibLaser.cxx - Adding Integral of B field
[u/mrichter/AliRoot.git] / STEER / AliAODHandler.cxx
1
2 /**************************************************************************
3  * Copyright(c) 1998-2007, ALICE Experiment at CERN, All rights reserved. *
4  *                                                                        *
5  * Author: The ALICE Off-line Project.                                    *
6  * Contributors are mentioned in the code where appropriate.              *
7  *                                                                        *
8  * Permission to use, copy, modify and distribute this software and its   *
9  * documentation strictly for non-commercial purposes is hereby granted   *
10  * without fee, provided that the above copyright notice appears in all   *
11  * copies and that both the copyright notice and this permission notice   *
12  * appear in the supporting documentation. The authors make no claims     *
13  * about the suitability of this software for any purpose. It is          *
14  * provided "as is" without express or implied warranty.                  *
15  **************************************************************************/
16
17 /* $Id$ */
18
19 //-------------------------------------------------------------------------
20 //     Implementation of the Virtual Event Handler Interface for AOD
21 //     Author: Andreas Morsch, CERN
22 //-------------------------------------------------------------------------
23
24
25 #include <TTree.h>
26 #include <TFile.h>
27 #include <TString.h>
28 #include <TList.h>
29 #include <TROOT.h>
30
31 #include "AliLog.h"
32 #include "AliAODHandler.h"
33 #include "AliAODEvent.h"
34 #include "AliAODTracklets.h"
35 #include "AliStack.h"
36 #include "AliAODMCParticle.h"
37 #include "AliAODMCHeader.h"
38 #include "AliMCEventHandler.h"
39 #include "AliMCEvent.h"
40 #include "AliGenEventHeader.h"
41 #include "AliGenHijingEventHeader.h"
42 #include "AliGenDPMjetEventHeader.h"
43 #include "AliGenPythiaEventHeader.h"
44 #include "AliGenCocktailEventHeader.h"
45
46
47
48 ClassImp(AliAODHandler)
49
50 //______________________________________________________________________________
51 AliAODHandler::AliAODHandler() :
52     AliVEventHandler(),
53     fIsStandard(kTRUE),
54     fFillAOD(kTRUE),
55     fNeedsHeaderReplication(kFALSE),
56     fNeedsTracksBranchReplication(kFALSE),
57     fNeedsVerticesBranchReplication(kFALSE),
58     fNeedsV0sBranchReplication(kFALSE),
59     fNeedsTrackletsBranchReplication(kFALSE),
60     fNeedsPMDClustersBranchReplication(kFALSE),
61     fNeedsJetsBranchReplication(kFALSE),
62     fNeedsFMDClustersBranchReplication(kFALSE),
63     fNeedsCaloClustersBranchReplication(kFALSE),
64     fNeedsMCParticlesBranchReplication(kFALSE),
65     fNeedsDimuonsBranchReplication(kFALSE),
66     fAODIsReplicated(kFALSE),
67     fAODEvent(NULL),
68     fMCEventH(NULL),
69     fTreeA(NULL),
70     fFileA(NULL),
71     fFileName(""),
72     fExtensions(NULL),
73     fFilters(NULL)
74 {
75   // default constructor
76 }
77
78 //______________________________________________________________________________
79 AliAODHandler::AliAODHandler(const char* name, const char* title):
80     AliVEventHandler(name, title),
81     fIsStandard(kTRUE),
82     fFillAOD(kTRUE),
83     fNeedsHeaderReplication(kFALSE),
84     fNeedsTracksBranchReplication(kFALSE),
85     fNeedsVerticesBranchReplication(kFALSE),
86     fNeedsV0sBranchReplication(kFALSE),
87     fNeedsTrackletsBranchReplication(kFALSE),
88     fNeedsPMDClustersBranchReplication(kFALSE),
89     fNeedsJetsBranchReplication(kFALSE),
90     fNeedsFMDClustersBranchReplication(kFALSE),
91     fNeedsCaloClustersBranchReplication(kFALSE),
92     fNeedsMCParticlesBranchReplication(kFALSE),
93     fNeedsDimuonsBranchReplication(kFALSE),
94     fAODIsReplicated(kFALSE),
95     fAODEvent(NULL),
96     fMCEventH(NULL),
97     fTreeA(NULL),
98     fFileA(NULL),
99     fFileName(""),
100     fExtensions(NULL),
101     fFilters(NULL)
102 {
103 // Normal constructor.
104 }
105
106 //______________________________________________________________________________
107 AliAODHandler::~AliAODHandler() 
108 {
109  // Destructor.
110   if (fAODEvent) delete fAODEvent;
111   if(fFileA){
112     // is already handled in TerminateIO
113     fFileA->Close();
114     delete fFileA;
115     fTreeA = 0;
116   }
117   if (fTreeA) delete fTreeA;
118   if (fExtensions) {fExtensions->Delete(); delete fExtensions;}
119   if (fFilters)    {fFilters->Delete();    delete fFilters;}
120 }
121
122 //______________________________________________________________________________
123 Bool_t AliAODHandler::Init(Option_t* opt)
124 {
125   // Initialize IO
126   //
127   // Create the AODevent object
128   Bool_t createStdAOD = fIsStandard || fFillAOD;
129   if(!fAODEvent && createStdAOD){
130     fAODEvent = new AliAODEvent();
131     if (fIsStandard) fAODEvent->CreateStdContent();
132   }
133   //
134   // File opening according to execution mode
135   TString option(opt);
136   option.ToLower();
137   if (createStdAOD) {
138     TDirectory *owd = gDirectory;
139     if (option.Contains("proof")) {
140       // proof
141       // Merging via files. Need to access analysis manager via interpreter.
142       gROOT->ProcessLine(Form("AliAnalysisDataContainer *c_common_out = AliAnalysisManager::GetAnalysisManager()->GetCommonOutputContainer();"));
143       gROOT->ProcessLine(Form("AliAnalysisManager::GetAnalysisManager()->OpenProofFile(c_common_out, \"RECREATE\");"));
144       fFileA = gFile;
145     } else {
146       // local and grid
147       fFileA = new TFile(fFileName.Data(), "RECREATE");
148     }
149     CreateTree(1);
150     owd->cd();
151   }  
152   if (fExtensions) {
153      TIter next(fExtensions);
154      AliAODExtension *ext;
155      while ((ext=(AliAODExtension*)next())) ext->Init(option);
156   }   
157   if (fFilters) {
158      TIter nextf(fFilters);
159      AliAODExtension *filteredAOD;
160      while ((filteredAOD=(AliAODExtension*)nextf())) {
161         filteredAOD->SetEvent(fAODEvent);
162         filteredAOD->Init(option);
163      }   
164   }   
165   return kTRUE;
166 }
167
168 //______________________________________________________________________________
169 void AliAODHandler::StoreMCParticles(){
170
171   // 
172   // Remap the labels from ESD stack and store
173   // the AODMCParticles, makes only sense if we have
174   // the mcparticles branch
175   // has to be done here since we cannot know in advance 
176   // which particles are needed (e.g. by the tracks etc.)
177   //
178   // Particles have been selected by AliMCEventhanlder->SelectParticle()
179   // To use the MCEventhandler here we need to set it from the outside
180   // can vanish when Handler go to the ANALYSISalice library
181   //
182   // The Branch booking for mcParticles and mcHeader has to happen 
183   // in an external task for now since the AODHandler does not have access
184   // the AnalysisManager. For the same reason the pointer t o the MCEventH
185   // has to passed to the AOD Handler by this task 
186   // (doing this in the steering macro would not work on PROOF)
187
188   if (!fAODEvent) return;
189   TClonesArray *mcarray = (TClonesArray*)fAODEvent->FindListObject(AliAODMCParticle::StdBranchName()); 
190   if(!mcarray)return;
191   mcarray->Delete();
192
193   AliAODMCHeader *mcHeader = (AliAODMCHeader*)fAODEvent->FindListObject(AliAODMCHeader::StdBranchName()); 
194   if(!mcHeader)return;
195
196   mcHeader->Reset();
197
198   // Get the MC Infos.. Handler needs to be set before 
199   // while adding the branch
200   // This needs to be done, not to depend on the AnalysisManager
201
202   if(!fMCEventH)return;
203   if(!fMCEventH->MCEvent())return;
204   AliStack *pStack = fMCEventH->MCEvent()->Stack();
205   if(!pStack)return;
206
207   fMCEventH->CreateLabelMap();
208
209   //
210   // Get the Event Header 
211   // 
212
213   AliHeader* header = fMCEventH->MCEvent()->Header();
214    // get the MC vertex
215   AliGenEventHeader* genHeader = 0;
216   if (header) genHeader = header->GenEventHeader();
217   if (genHeader) {
218       TArrayF vtxMC(3);
219       genHeader->PrimaryVertex(vtxMC);
220       mcHeader->SetVertex(vtxMC[0],vtxMC[1],vtxMC[2]);
221
222       // we search the MCEventHeaders first 
223       // Two cases, cocktail or not...
224       AliGenCocktailEventHeader* genCocktailHeader = dynamic_cast<AliGenCocktailEventHeader*>(genHeader);
225       if(genCocktailHeader){
226           // we have a coktail header
227           mcHeader->AddGeneratorName(genHeader->GetName());
228           // Loop from the back so that the first one sets the process type
229           TList* headerList = genCocktailHeader->GetHeaders();
230           for(int i = headerList->GetEntries()-1;i>=0;--i){
231               AliGenEventHeader *headerEntry = dynamic_cast<AliGenEventHeader*>(headerList->At(i));
232               SetMCHeaderInfo(mcHeader,headerEntry);
233           }
234       }
235       else{
236           // No Cocktail just take the first one
237           SetMCHeaderInfo(mcHeader,genHeader);
238       }
239   }
240   
241
242
243
244
245   // Store the AliAODParticlesMC
246   AliMCEvent* mcEvent = fMCEventH->MCEvent();
247   
248   Int_t np    = mcEvent->GetNumberOfTracks();
249   Int_t nprim = mcEvent->GetNumberOfPrimaries();
250
251
252   Int_t j = 0;
253   TClonesArray& l = *mcarray;
254
255   for(int i = 0; i < np; ++i){
256       if(fMCEventH->IsParticleSelected(i)){
257           Int_t flag = 0;
258           AliMCParticle* mcpart =  (AliMCParticle*) mcEvent->GetTrack(i);
259           if(i<nprim)flag |= AliAODMCParticle::kPrimary;
260           
261           if(mcEvent->IsPhysicalPrimary(i))flag |= AliAODMCParticle::kPhysicalPrim;
262           
263           if(fMCEventH->GetNewLabel(i)!=j){
264               AliError(Form("MISMATCH New label %d j: %d",fMCEventH->GetNewLabel(i),j));
265           }
266
267           AliAODMCParticle mcpart_tmp(mcpart,i,flag);
268           
269           mcpart_tmp.SetStatus(mcpart->Particle()->GetStatusCode());
270           // 
271           Int_t d0 =  mcpart_tmp.GetDaughter(0);
272           Int_t d1 =  mcpart_tmp.GetDaughter(1);
273           Int_t m =   mcpart_tmp.GetMother();
274           
275           // other than for the track labels, negative values mean
276           // no daughter/mother so preserve it
277           
278           if(d0<0 && d1<0){
279               // no first daughter -> no second daughter
280               // nothing to be done
281               // second condition not needed just for sanity check at the end
282               mcpart_tmp.SetDaughter(0,d0);
283               mcpart_tmp.SetDaughter(1,d1);
284           } else if(d1 < 0 && d0 >= 0) {
285               // Only one daughter
286               // second condition not needed just for sanity check at the end
287               if(fMCEventH->IsParticleSelected(d0)){
288                   mcpart_tmp.SetDaughter(0,fMCEventH->GetNewLabel(d0));
289               } else {
290                   mcpart_tmp.SetDaughter(0,-1);
291               }
292               mcpart_tmp.SetDaughter(1,d1);
293           }
294           else if (d0 > 0 && d1 > 0 ){
295               // we have two or more daughters loop on the stack to see if they are
296               // selected
297               Int_t d0_tmp = -1;
298               Int_t d1_tmp = -1;
299               for(int id = d0; id<=d1;++id){
300                   if(fMCEventH->IsParticleSelected(id)){
301                       if(d0_tmp==-1){
302                           // first time
303                           d0_tmp = fMCEventH->GetNewLabel(id);
304                           d1_tmp = d0_tmp; // this is to have the same schema as on the stack i.e. with one daugther d0 and d1 are the same 
305                       }
306                       else d1_tmp = fMCEventH->GetNewLabel(id);
307                   }
308               }
309               mcpart_tmp.SetDaughter(0,d0_tmp);
310               mcpart_tmp.SetDaughter(1,d1_tmp);
311           } else {
312               AliError(Form("Unxpected indices %d %d",d0,d1));
313           }
314           
315           if(m<0){
316               mcpart_tmp.SetMother(m);
317           } else {
318               if(fMCEventH->IsParticleSelected(m))mcpart_tmp.SetMother(fMCEventH->GetNewLabel(m));
319               else AliError(Form("PROBLEM Mother not selected %d \n", m));
320           }
321
322           new (l[j++]) AliAODMCParticle(mcpart_tmp);
323           
324       }
325   }
326   AliInfo(Form("AliAODHandler::StoreMCParticles: Selected %d (Primaries %d / total %d) after validation \n",
327                j,nprim,np));
328   
329   // Set the labels in the AOD output...
330   // Remapping
331
332   // AODTracks
333   TClonesArray* tracks = fAODEvent->GetTracks();
334   if(tracks){
335     for(int it = 0; it < fAODEvent->GetNTracks();++it){
336       AliAODTrack *track = fAODEvent->GetTrack(it);
337       
338       Int_t sign = 1;
339       Int_t label = track->GetLabel();
340       if(label<0){ // preserve the sign for later usage
341         label *= -1;
342         sign  = -1;
343       }
344
345       if (label >= AliMCEvent::BgLabelOffset()) label =  mcEvent->BgLabelToIndex(label);
346       if(label > np || track->GetLabel() == 0){
347         AliWarning(Form("Wrong ESD track label %5d (%5d)",track->GetLabel(), label));
348       }
349       if(fMCEventH->GetNewLabel(label) == 0){
350         AliWarning(Form("New label not found for %5d (%5d)",track->GetLabel(), label));
351       }
352       track->SetLabel(sign*fMCEventH->GetNewLabel(label));
353     }
354   }
355   
356   // AOD calo cluster
357   TClonesArray *clusters = fAODEvent->GetCaloClusters();
358   if(clusters){
359     for (Int_t iClust = 0;iClust < fAODEvent->GetNCaloClusters(); ++iClust) {
360       AliAODCaloCluster * cluster = fAODEvent->GetCaloCluster(iClust);
361       UInt_t nLabel    = cluster->GetNLabel();
362       // Ugly but do not want to fragment memory by creating 
363       // new Int_t (nLabel)
364       Int_t* labels    = const_cast<Int_t*>(cluster->GetLabels());
365       if (labels){
366         for(UInt_t i = 0;i < nLabel;++i){
367           labels[i] = fMCEventH->GetNewLabel(cluster->GetLabel(i));
368         }
369       }
370       //      cluster->SetLabels(labels,nLabel);
371     }// iClust
372   }// clusters
373
374   // AOD tracklets
375   AliAODTracklets *tracklets = fAODEvent->GetTracklets();
376   if(tracklets){
377     for(int it = 0;it < tracklets->GetNumberOfTracklets();++it){
378       int label0 = tracklets->GetLabel(it,0);
379       int label1 = tracklets->GetLabel(it,1);
380       if(label0>=0)label0 = fMCEventH->GetNewLabel(label0);      
381       if(label1>=0)label1 = fMCEventH->GetNewLabel(label1);
382       tracklets->SetLabel(it,0,label0);
383       tracklets->SetLabel(it,1,label1);
384     }
385   }
386
387 }
388
389 //______________________________________________________________________________
390 Bool_t AliAODHandler::FinishEvent()
391 {
392   // Fill data structures
393   if(fFillAOD){
394       fAODEvent->MakeEntriesReferencable();
395       // StoreMCParticles();
396       FillTree();
397       
398       if (fExtensions) {
399           TIter next(fExtensions);
400           AliAODExtension *ext;
401           while ((ext=(AliAODExtension*)next())) ext->FinishEvent();
402       }
403       if (fFilters) {   
404           TIter nextf(fFilters);
405           AliAODExtension *ext;
406           while ((ext=(AliAODExtension*)nextf())) {
407               ext->FinishEvent();
408           }  
409       }       
410   }  
411   if (fIsStandard) fAODEvent->ResetStd();
412   // Reset AOD replication flag
413   fAODIsReplicated = kFALSE;
414   return kTRUE;
415 }
416
417 //______________________________________________________________________________
418 Bool_t AliAODHandler::Terminate()
419 {
420   // Terminate 
421   AddAODtoTreeUserInfo();
422   if (fExtensions) {
423     TIter next(fExtensions);
424     AliAODExtension *ext;
425     while ((ext=(AliAODExtension*)next())) ext->GetTree()->GetUserInfo()->Add(ext->GetAOD());
426   }  
427   return kTRUE;
428 }
429
430 //______________________________________________________________________________
431 Bool_t AliAODHandler::TerminateIO()
432 {
433   // Terminate IO
434   if (fFileA) {
435     fFileA->Write();
436     fFileA->Close();
437     delete fFileA;
438     fFileA = 0;
439     // When closing the file, the tree is also deleted.
440     fTreeA = 0;
441   }
442   if (fExtensions) {
443     TIter next(fExtensions);
444     AliAODExtension *ext;
445     while ((ext=(AliAODExtension*)next())) ext->TerminateIO();
446   }  
447   if (fFilters) {
448     TIter nextf(fFilters);
449     AliAODExtension *ext;
450     while ((ext=(AliAODExtension*)nextf())) ext->TerminateIO();
451   }  
452   return kTRUE;
453 }
454
455 //______________________________________________________________________________
456 void AliAODHandler::CreateTree(Int_t flag)
457 {
458     // Creates the AOD Tree
459     fTreeA = new TTree("aodTree", "AliAOD tree");
460     fTreeA->Branch(fAODEvent->GetList());
461     fTreeA->BranchRef();    
462     if (flag == 0) fTreeA->SetDirectory(0);
463 }
464
465 //______________________________________________________________________________
466 void AliAODHandler::FillTree()
467 {
468  
469     // Fill the AOD Tree
470   fTreeA->Fill();
471 }
472
473 //______________________________________________________________________________
474 void AliAODHandler::AddAODtoTreeUserInfo()
475 {
476   // Add aod event to tree user info
477   if (fTreeA) fTreeA->GetUserInfo()->Add(fAODEvent);
478   // Now the tree owns our fAODEvent...
479   fAODEvent = 0;
480 }
481
482 //______________________________________________________________________________
483 void AliAODHandler::AddBranch(const char* cname, void* addobj, const char* filename)
484 {
485     // Add a new branch to the aod. Added optional filename parameter if the
486     // branch should be written to a separate file.
487     if (strlen(filename)) {
488        AliAODExtension *ext = AddExtension(filename);
489        ext->AddBranch(cname, addobj);
490        return;
491     }
492     TDirectory *owd = gDirectory;
493     if (fFileA) {
494       fFileA->cd();
495     }
496     char** apointer = (char**) addobj;
497     TObject* obj = (TObject*) *apointer;
498
499     fAODEvent->AddObject(obj);
500  
501     const Int_t kSplitlevel = 99; // default value in TTree::Branch()
502     const Int_t kBufsize = 32000; // default value in TTree::Branch()
503
504     if (!fTreeA->FindBranch(obj->GetName())) {
505       // Do the same as if we book via 
506       // TTree::Branch(TCollection*)
507       
508       fTreeA->Bronch(obj->GetName(), cname, fAODEvent->GetList()->GetObjectRef(obj),
509                      kBufsize, kSplitlevel - 1);
510       //    fTreeA->Branch(obj->GetName(), cname, addobj);
511     }
512     owd->cd();
513 }
514
515 //______________________________________________________________________________
516 AliAODExtension *AliAODHandler::AddExtension(const char *filename, const char *title)
517 {
518 // Add an AOD extension with some branches in a different file.
519    TString fname(filename);
520    if (!fname.EndsWith(".root")) fname += ".root";
521    if (!fExtensions) {
522       fExtensions = new TObjArray();
523       fExtensions->SetOwner();
524    }   
525    AliAODExtension *ext = (AliAODExtension*)fExtensions->FindObject(fname);
526    if (!ext) {
527       ext = new AliAODExtension(fname, title);
528       fExtensions->Add(ext);
529    }   
530    return ext;
531 }
532
533 //______________________________________________________________________________
534 AliAODExtension *AliAODHandler::GetExtension(const char *filename) const
535 {
536 // Getter for AOD extensions via file name.
537    if (!fExtensions) return NULL;
538    return (AliAODExtension*)fExtensions->FindObject(filename);
539 }   
540
541 //______________________________________________________________________________
542 AliAODExtension *AliAODHandler::AddFilteredAOD(const char *filename, const char *filtername)
543 {
544 // Add an AOD extension that can write only AOD events that pass a user filter.
545    if (!fFilters) {
546       fFilters = new TObjArray();
547       fFilters->SetOwner();
548    } 
549    AliAODExtension *filter = (AliAODExtension*)fFilters->FindObject(filename);
550    if (!filter) {
551       filter = new AliAODExtension(filename, filtername, kTRUE);
552       fFilters->Add(filter);
553    }
554    return filter;
555 }      
556
557 //______________________________________________________________________________
558 AliAODExtension *AliAODHandler::GetFilteredAOD(const char *filename) const
559 {
560 // Getter for AOD filters via file name.
561    if (!fFilters) return NULL;
562    return (AliAODExtension*)fFilters->FindObject(filename);
563 }   
564    
565 //______________________________________________________________________________
566 void AliAODHandler::SetOutputFileName(const char* fname)
567 {
568 // Set file name.
569    fFileName = fname;
570 }
571
572 //______________________________________________________________________________
573 const char *AliAODHandler::GetOutputFileName()
574 {
575 // Get file name.
576    return fFileName.Data();
577 }
578
579 //______________________________________________________________________________
580 void  AliAODHandler::SetMCHeaderInfo(AliAODMCHeader *mcHeader,AliGenEventHeader *genHeader){
581
582
583   // Utility function to cover different cases for the AliGenEventHeader
584   // Needed since different ProcessType and ImpactParamter are not 
585   // in the base class...
586   // We don't encode process types for event cocktails yet
587   // could be done e.g. by adding offsets depnding on the generator
588
589   mcHeader->AddGeneratorName(genHeader->GetName());
590   if(!genHeader)return;
591   AliGenPythiaEventHeader *pythiaGenHeader = dynamic_cast<AliGenPythiaEventHeader*>(genHeader);
592     if (pythiaGenHeader) {
593       mcHeader->SetEventType(pythiaGenHeader->ProcessType());
594       mcHeader->SetPtHard(pythiaGenHeader->GetPtHard());
595       return;
596     }
597     
598     AliGenDPMjetEventHeader* dpmJetGenHeader = dynamic_cast<AliGenDPMjetEventHeader*>(genHeader);
599
600   if (dpmJetGenHeader){
601     mcHeader->SetEventType(dpmJetGenHeader->ProcessType());
602     return;
603   } 
604
605   AliGenHijingEventHeader* hijingGenHeader = dynamic_cast<AliGenHijingEventHeader*>(genHeader);
606   if(hijingGenHeader){
607     mcHeader->SetImpactParameter(hijingGenHeader->ImpactParameter());
608     return;
609   }
610   
611   AliWarning(Form("MC Eventheader not known: %s",genHeader->GetName()));
612
613 }
614
615 ClassImp(AliAODExtension)
616
617 //-------------------------------------------------------------------------
618 //     Support class for AOD extensions. This is created by the user analysis
619 //     that requires a separate file for some AOD branches. The name of the 
620 //     AliAODExtension object is the file name where the AOD branches will be
621 //     stored.
622 //-------------------------------------------------------------------------
623
624 //______________________________________________________________________________
625 AliAODExtension::AliAODExtension(const char* name, const char* title, Bool_t isfilter)
626                 :TNamed(name,title), 
627                  fAODEvent(0), 
628                  fTreeE(0), 
629                  fFileE(0), 
630                  fNtotal(0), 
631                  fNpassed(0),
632                  fSelected(kFALSE)
633 {
634 // Constructor.
635   if (isfilter) {
636     TObject::SetBit(kFilteredAOD);
637     printf("####### Added AOD filter %s\n", name);
638   } else printf("####### Added AOD extension %s\n", name);
639 }   
640
641 //______________________________________________________________________________
642 AliAODExtension::~AliAODExtension()
643 {
644 // Destructor.
645   if(fFileE){
646     // is already handled in TerminateIO
647     fFileE->Close();
648     delete fFileE;
649     fTreeE = 0;
650     fAODEvent = 0;
651   }
652   if (fTreeE) delete fTreeE;
653 }
654
655 //______________________________________________________________________________
656 void AliAODExtension::AddBranch(const char* cname, void* addobj)
657 {
658     // Add a new branch to the aod 
659     if (IsFilteredAOD()) {
660        Error("AddBranch", "Not allowed to add branched to filtered AOD's.");
661        return;
662     }   
663     if (!fAODEvent) {
664        char type[20];
665        gROOT->ProcessLine(Form("TString s_tmp; AliAnalysisManager::GetAnalysisManager()->GetAnalysisTypeString(s_tmp); sprintf((char*)0x%lx, \"%%s\", s_tmp.Data());", type));
666        Init(type);
667     }
668     TDirectory *owd = gDirectory;
669     if (fFileE) {
670       fFileE->cd();
671     }
672     char** apointer = (char**) addobj;
673     TObject* obj = (TObject*) *apointer;
674
675     fAODEvent->AddObject(obj);
676  
677     const Int_t kSplitlevel = 99; // default value in TTree::Branch()
678     const Int_t kBufsize = 32000; // default value in TTree::Branch()
679
680     if (!fTreeE->FindBranch(obj->GetName())) {
681       // Do the same as if we book via 
682       // TTree::Branch(TCollection*)
683       
684       fTreeE->Bronch(obj->GetName(), cname, fAODEvent->GetList()->GetObjectRef(obj),
685                      kBufsize, kSplitlevel - 1);
686       //    fTreeA->Branch(obj->GetName(), cname, addobj);
687     }
688     owd->cd();
689 }
690
691 //______________________________________________________________________________
692 Bool_t AliAODExtension::FinishEvent()
693 {
694 // Fill current event.
695   fNtotal++;
696   if (!IsFilteredAOD()) {
697     fAODEvent->MakeEntriesReferencable();
698     fTreeE->Fill();
699     return kTRUE;
700   }  
701   // Filtered AOD. Fill only if event is selected.
702   if (!fSelected) return kTRUE;
703   fNpassed++;
704   fTreeE->Fill();
705   fSelected = kFALSE; // so that next event will not be selected unless demanded
706   return kTRUE;
707 }  
708
709 //______________________________________________________________________________
710 Bool_t AliAODExtension::Init(Option_t *option)
711 {
712 // Initialize IO.
713   if(!fAODEvent) fAODEvent = new AliAODEvent();
714   TDirectory *owd = gDirectory;
715   TString opt(option);
716   opt.ToLower();
717   if (opt.Contains("proof")) {
718     // proof
719     // Merging via files. Need to access analysis manager via interpreter.
720     gROOT->ProcessLine(Form("AliAnalysisManager::GetAnalysisManager()->OpenProofFile(\"%s\", \"RECREATE\");", fName.Data()));
721     fFileE = gFile;
722   } else {
723     fFileE = new TFile(GetName(), "RECREATE");
724   }  
725   fTreeE = new TTree("aodTree", "AliAOD tree");
726   fTreeE->Branch(fAODEvent->GetList());
727   fTreeE->BranchRef();
728   owd->cd();
729   return kTRUE;
730 }
731
732 //______________________________________________________________________________
733 void AliAODExtension::SetEvent(AliAODEvent *event)
734 {
735 // Connects to an external event
736    if (!IsFilteredAOD()) {
737       Error("SetEvent", "Not allowed to set external event for filtered AOD's");   
738       return;
739    }
740    // Use the copy constructor or assignment operator to synchronize with external event.
741 //   AliAODEvent &other = *event;
742 //   if (!fAODEvent)     fAODEvent = new AliAODEvent(other);
743 //   else if (fSelected) *fAODEvent = other;
744    fAODEvent = event;
745 }
746    
747 //______________________________________________________________________________
748 Bool_t AliAODExtension::TerminateIO()
749 {
750   // Terminate IO
751   if (TObject::TestBit(kFilteredAOD))
752     printf("AOD Filter %s: events processed: %d   passed: %d\n", GetName(), fNtotal, fNpassed);
753   else
754     printf("AOD extension %s: events processed: %d\n", GetName(), fNtotal);
755   if (fFileE) {
756     fFileE->Write();
757     fFileE->Close();
758     delete fFileE;
759     fFileE = 0;
760     fTreeE = 0;
761     fAODEvent = 0;
762   }
763   return kTRUE;
764 }