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