#include "PamRootManager.h"

#include <TParticle.h>
#include <TObjArray.h>

ClassImp(PamRootManager)

PamRootManager* PamRootManager::fgInstance = 0;

//_____________________________________________________________________________
PamRootManager::PamRootManager(const char* projectName, FileMode fileMode)
  : TObject()
{
//
  if (fgInstance) {
    Fatal("PamRootManager", "Singleton instance already exists.");
    return;
  }  

  TString fileName(projectName);
  fileName += ".root";

  TString treeTitle(projectName);
  treeTitle += " tree";

  switch (fileMode) {
    case kRead:
      fFile = new TFile(fileName);
      fTree = (TTree*) fFile->Get(projectName);
      break;
      
    case kWrite:  
      fFile = new TFile(fileName, "recreate");
      fTree = new TTree(projectName, treeTitle);
      ;;  
  }

  fgInstance = this;
}

//_____________________________________________________________________________
PamRootManager::PamRootManager()
  : TObject(),
    fFile(0),
    fTree(0) 
{
//   

  if (fgInstance) {
    Fatal("PamRootManager", "Singleton instance already exists.");
    return;
  }  

  fgInstance = this;
}

//_____________________________________________________________________________
PamRootManager::~PamRootManager() 
{
//
  delete fFile;
  fgInstance = 0;
}

//
// static methods
//

//_____________________________________________________________________________
PamRootManager* PamRootManager::Instance()
{
// Returns singleton instance.
// ---

  return fgInstance;
}  

//
// public methods
//

//_____________________________________________________________________________
void  PamRootManager::Register(const char* name, const char* className, 
                                void* objAddress)
{
// Creates a branch of the given name and associates it with
// the given address.
// ---

  if (!fTree->GetBranch(name)) 
    fTree->Branch(name, className, objAddress, 32000, 99);
  else  
    fTree->GetBranch(name)->SetAddress(objAddress);
}

//_____________________________________________________________________________
void  PamRootManager::Fill()
{
// Fills the tree.
// ---

  fTree->Fill();
}  

//_____________________________________________________________________________
void PamRootManager:: WriteAll()
{
// Erites the tree in the file.
// ---

  fTree->Write();
}  

//_____________________________________________________________________________
void  PamRootManager::ReadEvent(Int_t i)
{
// Reads the event data for i-th event for all connected branches.
// ---

  fTree->GetEntry(i);
}
