#include <string.h>
#include <stdio.h>
#include <iostream>
#include <vector>
#include <utility>

#include <TFile.h>
#include <TTree.h>
#include <TSystemDirectory.h>

#include "beammon.h"

using namespace std;

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

  // Working directories
  const char *dirname = "/work/leverington/beamprofilemonitor/hitdata/HIT_26-11-2016/with_timestamp/";
  const char *pin_dirname = "/work/leverington/beamprofilemonitor/hitdata/HIT_26-11-2016/with_timestamp/pin/";
  const char *ext = ".root";
  TSystemDirectory pin_dir(pin_dirname, pin_dirname);
  TList *files = pin_dir.GetListOfFiles();

  if (files)
  {
    TSystemFile* file;
    TString fname = ' ';
    TIter next(files);

    while ((file = (TSystemFile *)next()))
    {
      fname = file->GetName();

      // Loop over all files PiN_run***.root
      if (!file->IsDirectory() && fname.EndsWith(ext) && !fname.BeginsWith("SAVE") && fname.BeginsWith("PiN_run"))
      {
        Beammon *mon = new Beammon();
        printf("File name: %s \n", fname.Data());

        // Main part
        // Initialize(DIRName, FileName, baselineEvents, prelimEvents, beamLevel, firstFibermat, readOutFrequency in Hz, integrationTime in us)
        mon->Initialize(dirname, fname.Data(), 5000, 10000, 1., true, 3000., 312.);
        mon->Save();

        delete mon;
      }
    }
  }

  return 0;
}
