#include <stdio.h>
#include <TH1F.h>
#include <math.h>
#include <TFile.h>


#define BFSZ 0xFF

void oscar97test(const char *inF19 = "f19.list") {
  char buf[BFSZ] = {0};
  FILE *fList = fopen(inF19, "r");

  if (!fList) {
    printf("Can't open %s... exiting\n", inF19);
    return;
  }


  int evNum, nTracks, realEvNum = 0;
  int nTracks_real;
  float imp, planeRot;
  //
  Int_t id;
  Int_t pdgId;
  Float_t px, py, pz;
  Float_t energy, mass;
  Float_t xFr, yFr, zFr, tFr;

  while (!feof(fList)) {
    FILE *fIn = nextF19(fList);
    if (fIn) {
      //
      // Skip 3 useless lines at the
      // beginning
      //
      fgets(buf, BFSZ, fIn);
      fgets(buf, BFSZ, fIn);
      fgets(buf, BFSZ, fIn);

      while (!feof(fIn)) {
        //
        // Read event
        //
        int ret = fscanf(fIn, "%i %i %f %f",
                         &evNum, &nTracks, &imp, &planeRot);
        if (ret == 4) {
          realEvNum++;
          nTracks_real = 0;
          for (int iTrack = 0; iTrack < nTracks; iTrack++) {
            int ret1 =  fscanf(fIn,
                               " %i %i %f %f %f %f %f",
                               &id, &pdgId, &px, &py, &pz,
                               &energy, &mass);
            int ret2 = fscanf(fIn," %f %f %f %f",
                              &xFr, &yFr, &zFr, &tFr);
            if ((ret1 + ret2) != 11)
              break;
            else
              nTracks_real++;
          }
          std::cout << "event=" << evNum
              << " realEvNum=" << realEvNum
              << " Ntracks=" << nTracks
              << " NrealTracks=" << nTracks_real
              << " imp=" << imp
              << " planeRot=" << planeRot
              << std::endl;
          if (nTracks_real != nTracks) {
            std::cout << "nTracks_real != nTracks"
                << std::endl;
            break;
          }
        }
        else
          break;
      }
      fclose(fIn);
    }
  }
  fclose(fList);
}


FILE *nextF19(FILE *fList) {
  char buf[BFSZ] = {0};

  if (fgets(buf, BFSZ, fList)) {
    buf[strlen(buf) - 1] = '\0';
    FILE *f19 = fopen(buf, "r");
    if (!f19)
      printf("Can't open %s\nSkipping...\n", buf);
    else
      printf("File: %s\n", buf);
    return f19;
  }
  else {

    return 0;
  }
}
