/*
 * LiveTimeAction.cpp
 *
 *  Created on: 13/lug/2009
 *      Author: Nicola Mori
 */

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

#include "LiveTimeAction.h"

LiveTimeAction::LiveTimeAction(const char *actionName, TString outFileBase, vector<float> &bins, float thresholdCoeff) :
  Histo1DAction<Double_t> (actionName, "", outFileBase, "RECREATE", false, true), _thresholdCoeff(thresholdCoeff),
      _totalNorm(0.), _nGoodHisto(0), _nGoodInfBin(0) {
  SetXAxis("Live Time [s]", bins);
}

LiveTimeAction::LiveTimeAction(const char *actionName, TString outFileBase, TString rigBinsFile, float thresholdCoeff) :
  Histo1DAction<Double_t> (actionName, "", outFileBase, "RECREATE", false, true), _thresholdCoeff(thresholdCoeff),
      _totalNorm(0.), _nGoodHisto(0), _nGoodInfBin(0) {
  SetXAxis("Live Time [s]", rigBinsFile);
}

void LiveTimeAction::OnGood(PamLevel2 *event) {

  double lt = 0.16 * (double) event->GetTrigLevel2()->dltime[0] / 1000.; // In seconds
  float cRig = _thresholdCoeff * event->GetOrbitalInfo()->GetCutoffSVL();

  Fill(cRig, lt);

  if (cRig >= _bins[0]) {

    if (cRig < _bins.back()) {
      _totalNorm += lt; // use double for sums of many real numbers
      _nGoodHisto++;
    }
  }

  else if (cRig > 0.) {
    _nGoodInfBin++;
  }
}

void LiveTimeAction::Finalize() {

  if (_outFileBase != "") {

    // Write the text file
    // Using custom output procedure (instead of standard Histo1D::Finalize) to set output precision
    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 < GetHisto().size(); i++)
      outTextFile << GetHisto()[i] << "\n";
    outTextFile.close();
    outTextFile.open((_outFileBase + "-InfBin.txt").Data(), ios_base::out);
    outTextFile << GetLTInfBin() << endl;
    outTextFile.close();
    outTextFile.precision(oldPrec);
    outTextFile << resetiosflags(ios::floatfield);

  }
}
