/*
 * FluxHistoAction.cpp
 *
 *  Created on: 20-mag-2009
 *      Author: Nicola Mori
 */

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

#include "FluxHistoAction.h"

FluxHistoAction::FluxHistoAction(const char *actionName, TString outFileBase, TString rigBinsFile, TString mode) :
  CollectionAction(actionName), _outFileBase(outFileBase), _bins(0), _rootHisto(), _textHisto(0), _mode(mode)
#ifdef DEBUGPAMCUT
, _outUp(0), _outDown(0)
#endif
{

  // Reading the bins from file
  ifstream rigBinListFile;
  rigBinListFile.open(rigBinsFile);

  TString auxString;
  while (!rigBinListFile.eof()) {
    rigBinListFile >> auxString;
    if (auxString != "") {
      _bins.push_back(auxString.Atof());
    }
  }
  rigBinListFile.close();

  // Initializing histograms
  _textHisto.assign(_bins.size() - 1, 0);
  _rootHisto.SetName(GetName());
  _rootHisto.SetTitle("Rigidity histogram");
  _rootHisto.GetXaxis()->SetTitle("R");
  _rootHisto.GetYaxis()->SetTitle("Events");

  Double_t *auxArray = new Double_t[_bins.size()];

  for (unsigned int i = 0; i < _bins.size(); i++) {
    auxArray[i] = _bins[i];
  }

  _rootHisto.SetBins(_bins.size() - 1, auxArray);

  delete[] auxArray;
}

void FluxHistoAction::OnGood(PamLevel2 *event) {

  float rig = 1. / event->GetTrack(0)->GetTrkTrack()->GetDeflection();
  if (rig >= _bins[0]) {
    int i = 1;
    int binningSize = _bins.size();
    bool found = false;
    while (!found && i < binningSize) {
      if (rig < _bins[i])
        found = true;
      else
        i++;
    }
    if (found) {
      _textHisto[i - 1]++;
      _rootHisto.Fill(rig);
    }
#ifdef DEBUGPAMCUT
    else
    _outUp++;
#endif
  }
#ifdef DEBUGPAMCUT
  else
  _outDown++;
#endif

}

void FluxHistoAction::Finalize() {

  // Write the text file
  // Currently, text output doesn't support append.
  ofstream outTextFile((_outFileBase + ".txt").Data(), ios_base::out);
  streamsize oldPrec = cout.precision();
  streamsize newPrec = 4;
  outTextFile.precision(newPrec);
  outTextFile.setf(ios::fixed, ios::floatfield);
  for (unsigned int i = 0; i < _textHisto.size(); i++)
    outTextFile << _textHisto[i] << "\n";
  outTextFile.close();
  outTextFile.precision(oldPrec);
  outTextFile << resetiosflags(ios::floatfield);

  // Write the ROOT file
  TFile outRootFile((_outFileBase + ".root"), _mode);
  outRootFile.cd();
  _rootHisto.Write();
  outRootFile.Close();

#ifdef DEBUGPAMCUT
  cout << "Debug informations from " << GetName() << ":\n";
  cout << "   Events below the lowest rigidity: " << _outDown << "\n";
  cout << "   Events above the highest rigidity: " << _outUp << endl;
#endif
}
