/*
 * RigFillAction.cpp
 *
 *  Created on: 14/lug/2009
 *      Author: Nicola Mori
 */

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

#include "RigFillAction.h"

RigFillAction::RigFillAction(const char *actionName, TString outFileBase, vector<float> &bins, float thresholdCoeff,
    float chargeSign, bool spilloverFlag, float spilloverLimit, float mdrMin) :
  Histo2DAction<Float_t> (actionName, "", outFileBase, "RECREATE", false, true), _thresholdCoeff(thresholdCoeff),
      _chargeSign(chargeSign), _spilloverFlag(spilloverFlag), _spilloverLimit(spilloverLimit), _mdrMin(mdrMin) {

  SetXAxis("Rc [GV]", bins);
  SetYAxis("R [GV]", bins);
}

RigFillAction::RigFillAction(const char *actionName, TString outFileBase, TString rigBinsFile, float thresholdCoeff,
    float chargeSign, bool spilloverFlag, float spilloverLimit, float mdrMin) :
  Histo2DAction<Float_t> (actionName, "", outFileBase, "RECREATE", false, true), _thresholdCoeff(thresholdCoeff),
      _chargeSign(chargeSign), _spilloverFlag(spilloverFlag), _spilloverLimit(spilloverLimit), _mdrMin(mdrMin) {

  SetXAxis("Rc [GV]", rigBinsFile);
  SetYAxis("R [GV]", rigBinsFile);
}

void RigFillAction::OnGood(PamLevel2 *event) {

  float rigThreshold = _thresholdCoeff * event->GetOrbitalInfo()->GetCutoffSVL();
  float rig = 1. / event->GetTrack(0)->GetTrkTrack()->GetDeflection();

  // Compute deflection correction due to MDR cut
  if (_mdrMin > 0.) {
    Double_t F = 0.;
    if (_mdrMin > 300.) {
      F = 2.215e-4 * (log(_mdrMin) - log(300.));
    }
    rig = 1. / (1. / rig + F);
  }

  if (rig / _chargeSign > 0) { // Check if the particle has the right sign
    Fill(rigThreshold, rig);
  }
  else if (_spilloverFlag && fabs(rig) > _spilloverLimit) { // Check if it is a spillover event
    Fill(rigThreshold, _yBins.back() + 1.); // Place it in the Y overflow
  }

}

void RigFillAction::Finalize() {

  // Save the histogram
  Histo2DAction<Float_t>::Finalize();

  // Save the zero bins
  if (_outFileBase != "") {
    ofstream outTextFile((_outFileBase + "-InfBins.txt").Data(), ios_base::out);
    // XUnderflow is the vector of events whose Rc is below the lower histogram limit
    for (unsigned int i = 0; i < GetXUnderflow().size(); i++)
      outTextFile << GetXUnderflow()[i] << "\n";
    outTextFile.close();

    // Save the (spillover + rigidity overflow)
    if (_spilloverFlag) {
      ofstream outTextFile((_outFileBase + "-Spillover.txt").Data(), ios_base::out);
      // XUnderYOverflow is the number of (spillover + rigidity overflow) events with an underflowing critical rigidity
      outTextFile << GetXUnderYOverflow() << "\n";
      for (unsigned int i = 0; i < GetXUnderflow().size(); i++)
        // YOverflow are the (spillover + rigidity overflow) bins
        outTextFile << GetYOverflow()[i] << "\n";
      outTextFile.close();
    }
  }
}
