/*
 * MassVsRigHistoAction.cpp
 *
 *  Created on: 28-marth-2010
 *      Author: Vitaly Malakhov
 */

/*! @file MassVsRigHistoAction.cpp The MassVsRigHistoAction class implementation file. */

#include "MassVsRigHistoAction.h"
#include "TMath.h"

MassVsRigHistoAction::MassVsRigHistoAction(const char *actionName, TString outFileBase, TString mode,
    bool outRoot, bool outText, TString title, Int_t Z, TString rigBinFile) :
    Histo2DAction<Int_t> (actionName, title, outFileBase, mode, outRoot, outText), _Z(Z), _rigBinFile(rigBinFile){

}

void MassVsRigHistoAction::OnGood(PamLevel2 *event) {
    Float_t betaev = event->GetTrack(0)->GetToFTrack()->beta[12];
    Float_t rigev = 1./event->GetTrack(0)->GetTrkTrack()->GetDeflection();
    Float_t Mass = 0;
    if(TMath::Abs(betaev) <= 1.) Mass = _Z*rigev*sqrt(pow(betaev,-2)-1);
    else Mass = -_Z*rigev*sqrt(1-pow(betaev,-2));
    Fill(rigev, Mass);
}

void MassVsRigHistoAction::Finalize() {

    Histo2DAction<Int_t>::Finalize();

    ifstream binListFile;
    binListFile.open(_rigBinFile);

    TString auxString;
    _xRBins.resize(0);
    while (!binListFile.eof()) {
      binListFile >> auxString;
      if (auxString != "") {
        _xRBins.push_back(auxString.Atof());
      }
    }
    binListFile.close();

    TH1F tmphisto;
    tmphisto.SetBins(GetRootHisto()->GetNbinsY(),GetRootHisto()->GetXaxis()->GetXmin(),GetRootHisto()->GetXaxis()->GetXmax());

    for (UInt_t i=0; i < _xRBins.size()-1 ;i++){
	_fixedRigHisto.push_back(tmphisto);
	ostringstream ss1(ostringstream::out);
	ss1 << _xRBins[i];
	ostringstream ss2(ostringstream::out);
	ss2 << _xRBins[i+1];
	TString s1 = ss1.str();
	TString s2 = ss2.str();
	for(Int_t j = 0; j<s1.Sizeof()-1; j++) if(s1[j] == '.') s1[j] = 'p';
	for(Int_t j = 0; j<s2.Sizeof()-1; j++) if(s2[j] == '.') s2[j] = 'p';
	_fixedRigHisto[i].SetName((TString)GetName()+"_Rig"+s1+"_"+s2+"GV");
	_fixedRigHisto[i].SetTitle((TString)GetName()+"_Rig"+s1+"_"+s2+"GV");
	for(Int_t k = 0; k < GetRootHisto()->GetNbinsY(); k++){
	  Float_t sumbins = 0;
	  for(Int_t j = 0; j < GetRootHisto()->GetNbinsX(); j++){
	    if(GetRootHisto()->GetXaxis()->GetBinUpEdge(j) > _xRBins[i] && GetRootHisto()->GetXaxis()->GetBinLowEdge(j) < _xRBins[i+1]) sumbins += GetRootHisto()->GetBinContent(j,k);
	  }
	  _fixedRigHisto[i].SetBinContent(k,sumbins);
	}
    }
    TFile outRootFile((Histo2DAction<Int_t>::_outFileBase + ".root"), "UPDATE");
    outRootFile.cd();
    for (UInt_t i=0; i < _xRBins.size()-1 ;i++)
	_fixedRigHisto[i].Write();
    outRootFile.Close();

}
