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