#include "StHbtMaker/CorrFctn/gregsBPLCMSFrame3DCorrFctn.h"
#include <cstdio>
#include <sstream>

#ifdef __ROOT__
ClassImp(gregsBPLCMSFrame3DCorrFctn)
#endif

//_________________
gregsBPLCMSFrame3DCorrFctn::gregsBPLCMSFrame3DCorrFctn(char *title,
						       const int &nbins,
						       const float &QLo, const float &QHi) {

  stringstream TitNum,TitDen,TitQinv;
  TitNum.str("");TitDen.str("");TitQinv.str("");
  TitNum<<title<<"_Num";
  TitDen<<title<<"_Den";
  TitQinv<<title<<"_Qinv";

  // set up numerator
  mNumerator = new StHbt3FHisto(TitNum.str().c_str(),
				TitNum.str().c_str(),
				nbins,QLo,QHi,
				nbins,QLo,QHi,
				nbins,QLo,QHi);
  // set up denominator
  mDenominator = new StHbt3FHisto(TitDen.str().c_str(),
				  TitDen.str().c_str(),
				  nbins,QLo,QHi,
				  nbins,QLo,QHi,
				  nbins,QLo,QHi);
  // set up ave qInv
  mQinvHisto = new StHbt3FHisto(TitQinv.str().c_str(),
				TitQinv.str().c_str(),
				nbins,QLo,QHi,
				nbins,QLo,QHi,
				nbins,QLo,QHi);

  //added by gnigmat - I think we need it here
  mNumerator->SetDirectory(0);
  mDenominator->SetDirectory(0);
  mQinvHisto->SetDirectory(0);

  // to enable error bar calculation...
  mNumerator->Sumw2();
  mDenominator->Sumw2();
  mQinvHisto->Sumw2();
}

//_________________
gregsBPLCMSFrame3DCorrFctn::~gregsBPLCMSFrame3DCorrFctn() {

  delete mNumerator;
  delete mDenominator;
  delete mQinvHisto;
}

//_________________
void gregsBPLCMSFrame3DCorrFctn::WriteOutHistos() {
  mNumerator->Write();
  mDenominator->Write();
  mQinvHisto->Write();
}

//_________________
void gregsBPLCMSFrame3DCorrFctn::Finish() {
  
  //Just making the qInv weight correction
  mQinvHisto->Divide(mDenominator);
}


//_________________
void gregsBPLCMSFrame3DCorrFctn::AddRealPair(const StHbtPair* pair){

  if (mPairCut){
    if (!(mPairCut->Pass(pair))) return;
  }

  double qOut = fabs(pair->qOutCMS());
  double qSide = fabs(pair->qSideCMS());
  double qLong = fabs(pair->qLongCMS());

  mNumerator->Fill(qOut,qSide,qLong);
}

//_________________
void gregsBPLCMSFrame3DCorrFctn::AddMixedPair(const StHbtPair* pair){

  if (mPairCut){
    if (!(mPairCut->Pass(pair))) return;
  }

  double Qinv = fabs(pair->qInv()); 
  double qOut = fabs(pair->qOutCMS());
  double qSide = fabs(pair->qSideCMS());
  double qLong = fabs(pair->qLongCMS());

  mDenominator->Fill(qOut,qSide,qLong,1.0);
  mQinvHisto->Fill(qOut,qSide,qLong,Qinv);
}

//_________________
StHbtString gregsBPLCMSFrame3DCorrFctn::Report() {

  string stemp = "gregs LCMS Frame Bertsch-Pratt 3D Correlation Function Report:\n";
  char ctemp[100];
  sprintf(ctemp,"Number of entries in numerator:\t%E\n",mNumerator->GetEntries());
  stemp += ctemp;
  sprintf(ctemp,"Number of entries in denominator:\t%E\n",mDenominator->GetEntries());
  stemp += ctemp;
  sprintf(ctemp,"Number of entries in Qinv histo:\t%E\n",mQinvHisto->GetEntries());
  stemp += ctemp;

  StHbtString returnThis = stemp;
  return returnThis;
}
