#include <string>
#include <iostream>
#include <iomanip>

#include "JTools/JFunction1D_t.hh"
#include "JTools/JFunctionalMap_t.hh"
#include "JPhysics/JPDFTable.hh"

#include "Jeep/JParser.hh"
#include "Jeep/JMessage.hh"


/**
 * \file
 *
 * Program to merge interpolation tables of shower light for PDFs.
 * \author mdejong
 */
int main(int argc, char **argv)
{
  using namespace std;
  using namespace JPP;

  vector<string>      inputFile;
  string              outputFile;
  int                 debug;
  
  try {

    JParser<> zap("Program to merge interpolation tables of shower light for PDFs.");

    zap['f'] = make_field(inputFile);
    zap['o'] = make_field(outputFile);
    zap['d'] = make_field(debug)                  = 0;

    zap(argc, argv);
  }
  catch(const exception &error) {
    FATAL(error.what() << endl);
  }


  typedef JSplineFunction1D_t                                     JFunction1D_t;
  typedef JMAPLIST<JPolint1FunctionalMap,
		   JPolint1FunctionalMap,
		   JPolint1FunctionalGridMap,
		   JPolint1FunctionalGridMap>::maplist            JMapList_t;
  typedef JPDFTable<JFunction1D_t, JMapList_t>                    JPDF_t;

  JPDF_t pdf;

  bool clone = true;

  for (vector<string>::const_iterator file_name = inputFile.begin(); file_name != inputFile.end(); ++file_name) {

    NOTICE("loading input from file " << *file_name << "... " << flush);

    try {

      JPDF_t fcn;

      fcn.load(file_name->c_str());

      if (clone) {

	pdf.transformer.reset(fcn.transformer->clone());

	clone = false;
      }

      for (JPDF_t::super_const_iterator i = fcn.super_begin(); i != fcn.super_end(); ++i)
	pdf.insert(*i);
    }
    catch(const JException& error) {
      FATAL(error.what() << endl);
    }

    NOTICE("OK" << endl);
  }

  try {

    NOTICE("storing output to file " << outputFile << "... " << flush);

    pdf.store(outputFile.c_str());

    NOTICE("OK" << endl);
  }
  catch(const JException& error) {
    FATAL(error.what() << endl);
  }
}