using namespace std;
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <stdlib.h>
#include <math.h>

#include "HitEfficiency.h"

int main( int argc, char* argv[] ) {

  string seed_i( argv[1] );
  int seed;
  stringstream istr;
  istr.str( seed_i );
  istr >> seed;
  srandom( seed );

  // save file names
  string name_e( argv[2] );
  string name_r( argv[3] );

  // create efficiency model function
  HitEfficiency eFunc;
  eFunc.recover( name_e.c_str() );

  // boundaries
  float xMin = eFunc.xMin();
  float xMax = eFunc.xMax();

  // open output file
  ofstream file_r( name_r.c_str() );

  // set event number
  int maxEvent = 100000;

  // event counter
  int event = 0;

  while ( event++ < maxEvent ) {
    while ( true ) {
      // generate a hit uniformly distributed in [xMin,xMax]
      float x = xMin + ( random() * ( xMax - xMin ) / RAND_MAX );
      // test to accept or reject hit: 
      //   - generate a random number uniformly distributed in [0,1]
      //   - accept and write it if the random number is lower than efficiency,
      //     otherwise reject it and generate another one
      float t = random() * 1.0 / RAND_MAX;
      if ( t < eFunc( x ) ) {
        file_r << x << endl;
        break;
      }
    }
  }

  return 0;

}

