]> git.uio.no Git - u/mrichter/AliRoot.git/blobdiff - STEER/AliAODHandler.cxx
Do not reset a zero pointer to MC info
[u/mrichter/AliRoot.git] / STEER / AliAODHandler.cxx
index 6cc89095d50558a5d96167c92ebdc20e125abd59..696e9822125ad015c895630a9f77ef07f0fd1c4e 100644 (file)
@@ -1,3 +1,4 @@
+
 /**************************************************************************
  * Copyright(c) 1998-2007, ALICE Experiment at CERN, All rights reserved. *
  *                                                                        *
@@ -23,7 +24,6 @@
 
 #include <TTree.h>
 #include <TFile.h>
-#include <TRef.h>
 #include <TString.h>
 #include <TList.h>
 #include <TROOT.h>
@@ -52,22 +52,27 @@ AliAODHandler::AliAODHandler() :
     AliVEventHandler(),
     fIsStandard(kTRUE),
     fFillAOD(kTRUE),
+    fFillAODRun(kTRUE),
     fNeedsHeaderReplication(kFALSE),
     fNeedsTracksBranchReplication(kFALSE),
     fNeedsVerticesBranchReplication(kFALSE),
     fNeedsV0sBranchReplication(kFALSE),
+    fNeedsCascadesBranchReplication(kFALSE),
     fNeedsTrackletsBranchReplication(kFALSE),
     fNeedsPMDClustersBranchReplication(kFALSE),
     fNeedsJetsBranchReplication(kFALSE),
     fNeedsFMDClustersBranchReplication(kFALSE),
     fNeedsCaloClustersBranchReplication(kFALSE),
+    fNeedsMCParticlesBranchReplication(kFALSE),
+    fNeedsDimuonsBranchReplication(kFALSE),
     fAODIsReplicated(kFALSE),
     fAODEvent(NULL),
     fMCEventH(NULL),
     fTreeA(NULL),
     fFileA(NULL),
     fFileName(""),
-    fExtensions(NULL)
+    fExtensions(NULL),
+    fFilters(NULL)
 {
   // default constructor
 }
@@ -77,37 +82,45 @@ AliAODHandler::AliAODHandler(const char* name, const char* title):
     AliVEventHandler(name, title),
     fIsStandard(kTRUE),
     fFillAOD(kTRUE),
+    fFillAODRun(kTRUE),
     fNeedsHeaderReplication(kFALSE),
     fNeedsTracksBranchReplication(kFALSE),
     fNeedsVerticesBranchReplication(kFALSE),
     fNeedsV0sBranchReplication(kFALSE),
+    fNeedsCascadesBranchReplication(kFALSE),
     fNeedsTrackletsBranchReplication(kFALSE),
     fNeedsPMDClustersBranchReplication(kFALSE),
     fNeedsJetsBranchReplication(kFALSE),
     fNeedsFMDClustersBranchReplication(kFALSE),
     fNeedsCaloClustersBranchReplication(kFALSE),
+    fNeedsMCParticlesBranchReplication(kFALSE),
+    fNeedsDimuonsBranchReplication(kFALSE),
     fAODIsReplicated(kFALSE),
     fAODEvent(NULL),
     fMCEventH(NULL),
     fTreeA(NULL),
     fFileA(NULL),
     fFileName(""),
-    fExtensions(NULL)
+    fExtensions(NULL),
+    fFilters(NULL)
 {
+// Normal constructor.
 }
 
 //______________________________________________________________________________
 AliAODHandler::~AliAODHandler() 
 {
  // Destructor.
-  delete fAODEvent;
+  if (fAODEvent) delete fAODEvent;
   if(fFileA){
     // is already handled in TerminateIO
     fFileA->Close();
     delete fFileA;
+    fTreeA = 0;
   }
-  delete fTreeA;
-  if (fExtensions) delete fExtensions;
+  if (fTreeA) delete fTreeA;
+  if (fExtensions) {fExtensions->Delete(); delete fExtensions;}
+  if (fFilters)    {fFilters->Delete();    delete fFilters;}
 }
 
 //______________________________________________________________________________
@@ -116,8 +129,9 @@ Bool_t AliAODHandler::Init(Option_t* opt)
   // Initialize IO
   //
   // Create the AODevent object
-  printf(">>>> AliAODHandler::Init\n");
-  if(!fAODEvent){
+    
+  Bool_t createStdAOD = fIsStandard || fFillAOD;
+  if(!fAODEvent && createStdAOD){
     fAODEvent = new AliAODEvent();
     if (fIsStandard) fAODEvent->CreateStdContent();
   }
@@ -125,25 +139,34 @@ Bool_t AliAODHandler::Init(Option_t* opt)
   // File opening according to execution mode
   TString option(opt);
   option.ToLower();
-  TDirectory *owd = gDirectory;
-  if (option.Contains("proof")) {
-    // proof
-    // Merging via files. Need to access analysis manager via interpreter.
-    printf("Calling OpenProofFile()\n");
-    gROOT->ProcessLine(Form("AliAnalysisManager::GetAnalysisManager()->OpenProofFile(\"%s\", \"RECREATE\");", fFileName.Data()));
-    gROOT->ProcessLine(Form("AliAnalysisManager::GetAnalysisManager()->GetCommonOutputContainer()->SetFile((TFile*)0x%lx);", gFile));
-    fFileA = gFile;
-  } else {
-    // local and grid
-    fFileA = new TFile(fFileName.Data(), "RECREATE");
-  }
-  CreateTree(1);
-  owd->cd();
+  if (createStdAOD) {
+    TDirectory *owd = gDirectory;
+    if (option.Contains("proof")) {
+      // proof
+      // Merging via files. Need to access analysis manager via interpreter.
+      gROOT->ProcessLine(Form("AliAnalysisDataContainer *c_common_out = AliAnalysisManager::GetAnalysisManager()->GetCommonOutputContainer();"));
+      gROOT->ProcessLine(Form("AliAnalysisManager::GetAnalysisManager()->OpenProofFile(c_common_out, \"RECREATE\");"));
+      fFileA = gFile;
+    } else {
+      // local and grid
+      fFileA = new TFile(fFileName.Data(), "RECREATE");
+    }
+    CreateTree(1);
+    owd->cd();
+  }  
   if (fExtensions) {
      TIter next(fExtensions);
      AliAODExtension *ext;
      while ((ext=(AliAODExtension*)next())) ext->Init(option);
   }   
+  if (fFilters) {
+     TIter nextf(fFilters);
+     AliAODExtension *filteredAOD;
+     while ((filteredAOD=(AliAODExtension*)nextf())) {
+        filteredAOD->SetEvent(fAODEvent);
+        filteredAOD->Init(option);
+     }   
+  }   
   return kTRUE;
 }
 
@@ -167,15 +190,13 @@ void AliAODHandler::StoreMCParticles(){
   // has to passed to the AOD Handler by this task 
   // (doing this in the steering macro would not work on PROOF)
 
+  if (!fAODEvent) return;
   TClonesArray *mcarray = (TClonesArray*)fAODEvent->FindListObject(AliAODMCParticle::StdBranchName()); 
   if(!mcarray)return;
-  mcarray->Delete();
 
   AliAODMCHeader *mcHeader = (AliAODMCHeader*)fAODEvent->FindListObject(AliAODMCHeader::StdBranchName()); 
   if(!mcHeader)return;
 
-  mcHeader->Reset();
-
   // Get the MC Infos.. Handler needs to be set before 
   // while adding the branch
   // This needs to be done, not to depend on the AnalysisManager
@@ -192,118 +213,119 @@ void AliAODHandler::StoreMCParticles(){
   // 
 
   AliHeader* header = fMCEventH->MCEvent()->Header();
-  if (!header)return;
-
-  // get the MC vertex
-  AliGenEventHeader* genHeader = header->GenEventHeader();
-  TArrayF vtxMC(3);
-  genHeader->PrimaryVertex(vtxMC);
-  mcHeader->SetVertex(vtxMC[0],vtxMC[1],vtxMC[2]);
-
-  // we search the MCEventHeaders first 
-  // Two cases, cocktail or not...
-  AliGenCocktailEventHeader* genCocktailHeader = dynamic_cast<AliGenCocktailEventHeader*>(genHeader);
-  if(genCocktailHeader){
-    // we have a coktail header
-    mcHeader->AddGeneratorName(genHeader->GetName());
-    // Loop from the back so that the first one sets the process type
-    TList* headerList = genCocktailHeader->GetHeaders();
-    for(int i = headerList->GetEntries()-1;i>=0;--i){
-      AliGenEventHeader *headerEntry = dynamic_cast<AliGenEventHeader*>(headerList->At(i));
-      SetMCHeaderInfo(mcHeader,headerEntry);
-    }
-  }
-  else{
-    // No Cocktail just take the first one
-    SetMCHeaderInfo(mcHeader,genHeader);
+   // get the MC vertex
+  AliGenEventHeader* genHeader = 0;
+  if (header) genHeader = header->GenEventHeader();
+  if (genHeader) {
+      TArrayF vtxMC(3);
+      genHeader->PrimaryVertex(vtxMC);
+      mcHeader->SetVertex(vtxMC[0],vtxMC[1],vtxMC[2]);
+
+      // we search the MCEventHeaders first 
+      // Two cases, cocktail or not...
+      AliGenCocktailEventHeader* genCocktailHeader = dynamic_cast<AliGenCocktailEventHeader*>(genHeader);
+      if(genCocktailHeader){
+         // we have a coktail header
+         mcHeader->AddGeneratorName(genHeader->GetName());
+         // Loop from the back so that the first one sets the process type
+         TList* headerList = genCocktailHeader->GetHeaders();
+         for(int i = headerList->GetEntries()-1;i>=0;--i){
+             AliGenEventHeader *headerEntry = dynamic_cast<AliGenEventHeader*>(headerList->At(i));
+             SetMCHeaderInfo(mcHeader,headerEntry);
+         }
+      }
+      else{
+         // No Cocktail just take the first one
+         SetMCHeaderInfo(mcHeader,genHeader);
+      }
   }
+  
 
 
 
 
   // Store the AliAODParticlesMC
-
-  Int_t np    = pStack->GetNtrack();
-  Int_t nprim = pStack->GetNprimary();
+  AliMCEvent* mcEvent = fMCEventH->MCEvent();
+  
+  Int_t np    = mcEvent->GetNumberOfTracks();
+  Int_t nprim = mcEvent->GetNumberOfPrimaries();
 
 
   Int_t j = 0;
   TClonesArray& l = *mcarray;
 
-  for(int i = 0;i < np;++i){
-    if(fMCEventH->IsParticleSelected(i)){
-
-      Int_t flag = 0;
-      TParticle *part = pStack->Particle(i);
-      if(i<nprim)flag |= AliAODMCParticle::kPrimary;
-      if(pStack->IsPhysicalPrimary(i))flag |= AliAODMCParticle::kPhysicalPrim;
-
-      if(fMCEventH->GetNewLabel(i)!=j){
-       AliError(Form("MISMATCH New label %d j: %d",fMCEventH->GetNewLabel(i),j));
-      }
-      AliAODMCParticle mcpart_tmp(part,i,flag);
-
-      // 
-      Int_t d0 =  mcpart_tmp.GetDaughter(0);
-      Int_t d1 =  mcpart_tmp.GetDaughter(1);
-      Int_t m =  mcpart_tmp.GetMother();
+  for(int i = 0; i < np; ++i){
+      if(fMCEventH->IsParticleSelected(i)){
+         Int_t flag = 0;
+         AliMCParticle* mcpart =  (AliMCParticle*) mcEvent->GetTrack(i);
+         if(i<nprim)flag |= AliAODMCParticle::kPrimary;
+         
+         if(mcEvent->IsPhysicalPrimary(i))flag |= AliAODMCParticle::kPhysicalPrim;
+         
+         if(fMCEventH->GetNewLabel(i)!=j){
+             AliError(Form("MISMATCH New label %d j: %d",fMCEventH->GetNewLabel(i),j));
+         }
 
-      // other than for the track labels, negative values mean
-      // no daughter/mother so preserve it
-      if(d0<0 && d1<0){
-       // no first daughter -> no second daughter
-       // nothing to be done
-       // second condition not needed just for sanity check at the end
-       mcpart_tmp.SetDaughter(0,d0);
-       mcpart_tmp.SetDaughter(1,d1);
-      }
-      else if(d1 < 0 && d0 >= 0){
-       // Only one daughter
-       // second condition not needed just for sanity check at the end
-       if(fMCEventH->IsParticleSelected(d0)){
-         mcpart_tmp.SetDaughter(0,fMCEventH->GetNewLabel(d0));
-       }
-       else{
-         mcpart_tmp.SetDaughter(0,-1);
-       }
-       mcpart_tmp.SetDaughter(1,d1);
-      }
-      else if (d0 > 0 && d1 > 0 ){
-       // we have two or more daughters loop on the stack to see if they are
-       // selected
-       Int_t d0_tmp = -1;
-       Int_t d1_tmp = -1;
-       for(int id = d0; id<=d1;++id){
-         if(fMCEventH->IsParticleSelected(id)){
-           if(d0_tmp==-1){
-             // first time
-             d0_tmp = fMCEventH->GetNewLabel(id);
-             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 
-           }
-           else d1_tmp = fMCEventH->GetNewLabel(id);
+         AliAODMCParticle mcpart_tmp(mcpart,i,flag);
+         
+         mcpart_tmp.SetStatus(mcpart->Particle()->GetStatusCode());
+         // 
+         Int_t d0 =  mcpart_tmp.GetDaughter(0);
+         Int_t d1 =  mcpart_tmp.GetDaughter(1);
+         Int_t m =   mcpart_tmp.GetMother();
+         
+         // other than for the track labels, negative values mean
+         // no daughter/mother so preserve it
+         
+         if(d0<0 && d1<0){
+             // no first daughter -> no second daughter
+             // nothing to be done
+             // second condition not needed just for sanity check at the end
+             mcpart_tmp.SetDaughter(0,d0);
+             mcpart_tmp.SetDaughter(1,d1);
+         } else if(d1 < 0 && d0 >= 0) {
+             // Only one daughter
+             // second condition not needed just for sanity check at the end
+             if(fMCEventH->IsParticleSelected(d0)){
+                 mcpart_tmp.SetDaughter(0,fMCEventH->GetNewLabel(d0));
+             } else {
+                 mcpart_tmp.SetDaughter(0,-1);
+             }
+             mcpart_tmp.SetDaughter(1,d1);
+         }
+         else if (d0 > 0 && d1 > 0 ){
+             // we have two or more daughters loop on the stack to see if they are
+             // selected
+             Int_t d0_tmp = -1;
+             Int_t d1_tmp = -1;
+             for(int id = d0; id<=d1;++id){
+                 if(fMCEventH->IsParticleSelected(id)){
+                     if(d0_tmp==-1){
+                         // first time
+                         d0_tmp = fMCEventH->GetNewLabel(id);
+                         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 
+                     }
+                     else d1_tmp = fMCEventH->GetNewLabel(id);
+                 }
+             }
+             mcpart_tmp.SetDaughter(0,d0_tmp);
+             mcpart_tmp.SetDaughter(1,d1_tmp);
+         } else {
+             AliError(Form("Unxpected indices %d %d",d0,d1));
+         }
+         
+         if(m<0){
+             mcpart_tmp.SetMother(m);
+         } else {
+             if(fMCEventH->IsParticleSelected(m))mcpart_tmp.SetMother(fMCEventH->GetNewLabel(m));
+             else AliError(Form("PROBLEM Mother not selected %d \n", m));
          }
-       }
-       mcpart_tmp.SetDaughter(0,d0_tmp);
-       mcpart_tmp.SetDaughter(1,d1_tmp);
-      }
-      else{
-       AliError(Form("Unxpected indices %d %d",d0,d1));
-      }
 
-      if(m<0){
-       mcpart_tmp.SetMother(m);
-      }
-      else{
-       if(fMCEventH->IsParticleSelected(m))mcpart_tmp.SetMother(fMCEventH->GetNewLabel(m));
-       else AliError("PROBLEM Mother not selected");
+         new (l[j++]) AliAODMCParticle(mcpart_tmp);
+         
       }
-
-      new (l[j++]) AliAODMCParticle(mcpart_tmp);
-      
-    }
   }
-  AliInfo(Form("AliAODHandler::StoreMCParticles: Selected %d (Primaries %d / total %d) after validation",
+  AliInfo(Form("AliAODHandler::StoreMCParticles: Selected %d (Primaries %d / total %d) after validation \n",
               j,nprim,np));
   
   // Set the labels in the AOD output...
@@ -315,13 +337,21 @@ void AliAODHandler::StoreMCParticles(){
     for(int it = 0; it < fAODEvent->GetNTracks();++it){
       AliAODTrack *track = fAODEvent->GetTrack(it);
       
-      if(TMath::Abs(track->GetLabel())>np||track->GetLabel()==0){
-       AliWarning(Form("Wrong ESD track label %d",track->GetLabel()));
+      Int_t sign = 1;
+      Int_t label = track->GetLabel();
+      if(label<0){ // preserve the sign for later usage
+       label *= -1;
+       sign  = -1;
       }
-      if(fMCEventH->GetNewLabel(track->GetLabel())==0){
-       AliWarning(Form("New label not found for %d",track->GetLabel()));
+
+      if (label >= AliMCEvent::BgLabelOffset()) label =  mcEvent->BgLabelToIndex(label);
+      if(label > np || track->GetLabel() == 0){
+       AliWarning(Form("Wrong ESD track label %5d (%5d)",track->GetLabel(), label));
+      }
+      if(fMCEventH->GetNewLabel(label) == 0){
+       AliWarning(Form("New label not found for %5d (%5d)",track->GetLabel(), label));
       }
-      track->SetLabel(fMCEventH->GetNewLabel(track->GetLabel()));
+      track->SetLabel(sign*fMCEventH->GetNewLabel(label));
     }
   }
   
@@ -362,21 +392,33 @@ void AliAODHandler::StoreMCParticles(){
 Bool_t AliAODHandler::FinishEvent()
 {
   // Fill data structures
-  if(fFillAOD){
-    fAODEvent->MakeEntriesReferencable();
-    StoreMCParticles();
-    FillTree();
-    if (fExtensions) {
-      TIter next(fExtensions);
-      AliAODExtension *ext;
-      while ((ext=(AliAODExtension*)next())) {
-        ext->GetAOD()->MakeEntriesReferencable();
-        ext->GetTree()->Fill();
-      }  
-    }       
+  if(fFillAOD && fFillAODRun && fAODEvent){
+      fAODEvent->MakeEntriesReferencable();
+      fTreeA->BranchRef();
+      FillTree();
   }
 
+  if (fFillAOD) {      
+      if (fExtensions) {
+         TIter next(fExtensions);
+         AliAODExtension *ext;
+         while ((ext=(AliAODExtension*)next())) ext->FinishEvent();
+      }
+      if (fFilters) {   
+         TIter nextf(fFilters);
+         AliAODExtension *ext;
+         while ((ext=(AliAODExtension*)nextf())) {
+             ext->FinishEvent();
+         }  
+      }       
+  }  
   if (fIsStandard) fAODEvent->ResetStd();
+  TClonesArray *mcarray = (TClonesArray*)fAODEvent->FindListObject(AliAODMCParticle::StdBranchName()); 
+  if(mcarray) mcarray->Delete();
+
+  AliAODMCHeader *mcHeader = (AliAODMCHeader*)fAODEvent->FindListObject(AliAODMCHeader::StdBranchName()); 
+  if(mcHeader) mcHeader->Reset();
+
   // Reset AOD replication flag
   fAODIsReplicated = kFALSE;
   return kTRUE;
@@ -400,15 +442,23 @@ Bool_t AliAODHandler::TerminateIO()
 {
   // Terminate IO
   if (fFileA) {
+    fFileA->Write();
     fFileA->Close();
     delete fFileA;
     fFileA = 0;
+    // When closing the file, the tree is also deleted.
+    fTreeA = 0;
   }
   if (fExtensions) {
     TIter next(fExtensions);
     AliAODExtension *ext;
     while ((ext=(AliAODExtension*)next())) ext->TerminateIO();
   }  
+  if (fFilters) {
+    TIter nextf(fFilters);
+    AliAODExtension *ext;
+    while ((ext=(AliAODExtension*)nextf())) ext->TerminateIO();
+  }  
   return kTRUE;
 }
 
@@ -418,22 +468,24 @@ void AliAODHandler::CreateTree(Int_t flag)
     // Creates the AOD Tree
     fTreeA = new TTree("aodTree", "AliAOD tree");
     fTreeA->Branch(fAODEvent->GetList());
-    TRef junk = (TObject*)fTreeA->BranchRef();
     if (flag == 0) fTreeA->SetDirectory(0);
 }
 
 //______________________________________________________________________________
 void AliAODHandler::FillTree()
 {
     // Fill the AOD Tree
-  fTreeA->Fill();
+    fTreeA->Fill();
 }
 
 //______________________________________________________________________________
 void AliAODHandler::AddAODtoTreeUserInfo()
 {
   // Add aod event to tree user info
-  fTreeA->GetUserInfo()->Add(fAODEvent);
+  if (fTreeA) fTreeA->GetUserInfo()->Add(fAODEvent);
+  // Now the tree owns our fAODEvent...
+  fAODEvent = 0;
 }
 
 //______________________________________________________________________________
@@ -464,7 +516,6 @@ void AliAODHandler::AddBranch(const char* cname, void* addobj, const char* filen
       
       fTreeA->Bronch(obj->GetName(), cname, fAODEvent->GetList()->GetObjectRef(obj),
                     kBufsize, kSplitlevel - 1);
-      //    fTreeA->Branch(obj->GetName(), cname, addobj);
     }
     owd->cd();
 }
@@ -486,6 +537,38 @@ AliAODExtension *AliAODHandler::AddExtension(const char *filename, const char *t
    }   
    return ext;
 }
+
+//______________________________________________________________________________
+AliAODExtension *AliAODHandler::GetExtension(const char *filename) const
+{
+// Getter for AOD extensions via file name.
+   if (!fExtensions) return NULL;
+   return (AliAODExtension*)fExtensions->FindObject(filename);
+}   
+
+//______________________________________________________________________________
+AliAODExtension *AliAODHandler::AddFilteredAOD(const char *filename, const char *filtername)
+{
+// Add an AOD extension that can write only AOD events that pass a user filter.
+   if (!fFilters) {
+      fFilters = new TObjArray();
+      fFilters->SetOwner();
+   } 
+   AliAODExtension *filter = (AliAODExtension*)fFilters->FindObject(filename);
+   if (!filter) {
+      filter = new AliAODExtension(filename, filtername, kTRUE);
+      fFilters->Add(filter);
+   }
+   return filter;
+}      
+
+//______________________________________________________________________________
+AliAODExtension *AliAODHandler::GetFilteredAOD(const char *filename) const
+{
+// Getter for AOD filters via file name.
+   if (!fFilters) return NULL;
+   return (AliAODExtension*)fFilters->FindObject(filename);
+}   
    
 //______________________________________________________________________________
 void AliAODHandler::SetOutputFileName(const char* fname)
@@ -516,6 +599,7 @@ void  AliAODHandler::SetMCHeaderInfo(AliAODMCHeader *mcHeader,AliGenEventHeader
   AliGenPythiaEventHeader *pythiaGenHeader = dynamic_cast<AliGenPythiaEventHeader*>(genHeader);
     if (pythiaGenHeader) {
       mcHeader->SetEventType(pythiaGenHeader->ProcessType());
+      mcHeader->SetPtHard(pythiaGenHeader->GetPtHard());
       return;
     }
     
@@ -545,24 +629,50 @@ ClassImp(AliAODExtension)
 //     stored.
 //-------------------------------------------------------------------------
 
+//______________________________________________________________________________
+AliAODExtension::AliAODExtension(const char* name, const char* title, Bool_t isfilter)
+                :TNamed(name,title), 
+                 fAODEvent(0), 
+                 fTreeE(0), 
+                 fFileE(0), 
+                 fNtotal(0), 
+                 fNpassed(0),
+                 fSelected(kFALSE)
+{
+// Constructor.
+  if (isfilter) {
+    TObject::SetBit(kFilteredAOD);
+    printf("####### Added AOD filter %s\n", name);
+  } else printf("####### Added AOD extension %s\n", name);
+}   
+
 //______________________________________________________________________________
 AliAODExtension::~AliAODExtension()
 {
 // Destructor.
-  delete fAODEvent;
   if(fFileE){
     // is already handled in TerminateIO
     fFileE->Close();
     delete fFileE;
+    fTreeE = 0;
+    fAODEvent = 0;
   }
-  delete fTreeE;
+  if (fTreeE) delete fTreeE;
 }
 
 //______________________________________________________________________________
 void AliAODExtension::AddBranch(const char* cname, void* addobj)
 {
     // Add a new branch to the aod 
-    if (!fAODEvent) Init("");
+    if (IsFilteredAOD()) {
+       Error("AddBranch", "Not allowed to add branched to filtered AOD's.");
+       return;
+    }   
+    if (!fAODEvent) {
+       char type[20];
+       gROOT->ProcessLine(Form("TString s_tmp; AliAnalysisManager::GetAnalysisManager()->GetAnalysisTypeString(s_tmp); sprintf((char*)0x%lx, \"%%s\", s_tmp.Data());", type));
+       Init(type);
+    }
     TDirectory *owd = gDirectory;
     if (fFileE) {
       fFileE->cd();
@@ -578,14 +688,30 @@ void AliAODExtension::AddBranch(const char* cname, void* addobj)
     if (!fTreeE->FindBranch(obj->GetName())) {
       // Do the same as if we book via 
       // TTree::Branch(TCollection*)
-      
       fTreeE->Bronch(obj->GetName(), cname, fAODEvent->GetList()->GetObjectRef(obj),
                     kBufsize, kSplitlevel - 1);
-      //    fTreeA->Branch(obj->GetName(), cname, addobj);
     }
     owd->cd();
 }
 
+//______________________________________________________________________________
+Bool_t AliAODExtension::FinishEvent()
+{
+// Fill current event.
+  fNtotal++;
+  if (!IsFilteredAOD()) {
+    fAODEvent->MakeEntriesReferencable();
+    fTreeE->Fill();
+    return kTRUE;
+  }  
+  // Filtered AOD. Fill only if event is selected.
+  if (!fSelected) return kTRUE;
+  fNpassed++;
+  fTreeE->Fill();
+  fSelected = kFALSE; // so that next event will not be selected unless demanded
+  return kTRUE;
+}  
+
 //______________________________________________________________________________
 Bool_t AliAODExtension::Init(Option_t *option)
 {
@@ -604,20 +730,41 @@ Bool_t AliAODExtension::Init(Option_t *option)
   }  
   fTreeE = new TTree("aodTree", "AliAOD tree");
   fTreeE->Branch(fAODEvent->GetList());
-  TRef junk = (TObject*)fTreeE->BranchRef();
+  fTreeE->BranchRef();
   owd->cd();
   return kTRUE;
 }
 
+//______________________________________________________________________________
+void AliAODExtension::SetEvent(AliAODEvent *event)
+{
+// Connects to an external event
+   if (!IsFilteredAOD()) {
+      Error("SetEvent", "Not allowed to set external event for filtered AOD's");   
+      return;
+   }
+   // Use the copy constructor or assignment operator to synchronize with external event.
+//   AliAODEvent &other = *event;
+//   if (!fAODEvent)     fAODEvent = new AliAODEvent(other);
+//   else if (fSelected) *fAODEvent = other;
+   fAODEvent = event;
+}
+   
 //______________________________________________________________________________
 Bool_t AliAODExtension::TerminateIO()
 {
   // Terminate IO
+  if (TObject::TestBit(kFilteredAOD))
+    printf("AOD Filter %s: events processed: %d   passed: %d\n", GetName(), fNtotal, fNpassed);
+  else
+    printf("AOD extension %s: events processed: %d\n", GetName(), fNtotal);
   if (fFileE) {
     fFileE->Write();
     fFileE->Close();
     delete fFileE;
     fFileE = 0;
+    fTreeE = 0;
+    fAODEvent = 0;
   }
   return kTRUE;
 }