#include "HitEfficiency.h"

#include <iostream>
#include <fstream>
#include <math.h>

using namespace std;

HitEfficiency::HitEfficiency():
 wCell(  2.1 ),
 efMax(  1.0 ),
 slope(  0.0 ),
 iNorm( -0.5 ),
 width(  0.05 ) {
}

HitEfficiency::HitEfficiency( const char* fileName ):
 wCell(  2.1 ),
 efMax(  1.0 ),
 slope(  0.0 ),
 iNorm( -0.5 ),
 width(  0.05 ) {
  recover( fileName );
}

HitEfficiency::~HitEfficiency() {
}

// functions to get the boundaries
float HitEfficiency::xMin() const {
  return 0.0;
}

float HitEfficiency::xMax() const {
  return wCell;
}

float HitEfficiency::fMax() const {
  // limit max efficiency at 1
  return ( efMax < 1.0 ? efMax : 1.0 );
}

// operator function to get efficiency for distance x
float HitEfficiency::operator()( float x ) const {
  // for x outside boundaries return 0
  if ( x < xMin() ) return 0.0;
  if ( x > xMax() ) return 0.0;
  // compute efficiency
  float p = ( efMax + ( slope * x ) ) +
            ( iNorm / exp( pow( ( x - wCell ) / width, 2 ) / 2.0 ) );
  // force efficiency inside range [0,1]
  if ( p > fMax() ) return fMax();
  if ( p < 0.0    ) return 0.0;
  return p;
}

// functions to dump or recover function parameters to/from a text file
void HitEfficiency::dump( const char* fileName ) const {
  ofstream file( fileName );
  file << efMax << endl;
  file << slope << endl;
  file << iNorm << endl;
  file << width << endl;
  return;
}

void HitEfficiency::recover( const char* fileName ) {
  ifstream file( fileName );
  file >> efMax;
  file >> slope;
  file >> iNorm;
  file >> width;
  return;
}

