#include "PamRootManager.h"
#include <TSystem.h>
#include <TParticle.h>
#include <TObjArray.h>
#include <iostream>

#include <TList.h>
#include <TROOT.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 = TString(gSystem->Getenv("PWD"))+"/"+projectName;
  fileName += ".root";


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

  TTree::SetMaxTreeSize(1000*Long64_t(2000000000));

  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() 
{
  fFile->cd();
  delete fFile;
  delete fDirectory;
  fgInstance = 0;
}

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

  return fgInstance;
}  

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.
  //TString tmp = gDirectory->GetName();
  fFile->cd();
  fTree->Fill();
  //gDirectory->cd(tmp);
}  

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

  //TString tmp = gDirectory->GetName();  
  fFile->cd();
  std::cout<<"TREE NAME: "<<fTree->GetName()<<std::endl;
  std::cout<<"DIR NAME: "<<gDirectory->GetName()<<std::endl;
  fTree->Write();
  //gDirectory->cd(tmp);
  std::cout<<"TREE WRITTEN "<<fTree->GetName()<<std::endl;
}  

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

  fTree->GetEntry(i);
}
