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


#define BFSZ 0xFF


FILE *nextF19(FILE *fList);


void oscar97merger(const char *inF19  = "f19.list",
                   const char *outF19 = "OutSum.f19") {
  char buf[BFSZ] = {0};

  FILE *fList = fopen(inF19, "r");
  if (!fList) {
    printf("Can't open list file %s\nExiting...\n", inF19);
    return;
  }

  FILE *fOut = fopen(outF19, "w");
  if (!fOut) {
    printf("Can't create output file %s\nExiting...\n", outF19);
    return;
  }


  bool firstFile = true;
  int evNum, nTracks, realEvNum = 0, trRd = 0;
  float imp, planeRot;
  bool readEvent = true;
  while (!feof(fList)) {
    FILE *f19 = nextF19(fList);
    if (!f19)
      continue;
    //
    // Read header (first 3 lines) of the
    // first f19 file
    //
    if (firstFile) {
      fgets(buf, BFSZ, f19);
      fputs(buf, fOut);

      fgets(buf, BFSZ, f19);
      fputs(buf,  fOut);

      fgets(buf, BFSZ, f19);
      fputs(buf, fOut);

      firstFile = false;
    }
    else {
      //
      // skip three useless lines
      //
      fgets(buf, BFSZ, f19);
      fgets(buf, BFSZ, f19);
      fgets(buf, BFSZ, f19);
    }

    //
    // Read events and tracks
    //
    while (!feof(f19)) {
      if (readEvent) {
        int ret = fscanf(f19, "%i %i %f %f", &evNum, &nTracks, &imp, &planeRot);
        if (ret == 4) {
          /*
             printf("EVENT INFO:\n\t ID = %i, NTRACKS = %i, IMP =  %f, PLANEROT = %f, REAL_EVENT_NUM = %i\n",
             evNum, nTracks, imp, planeRot, realEvNum);
             */
          readEvent = false;
          realEvNum++;
          fprintf(fOut, "%10i  %10i  %8.3f  %8.3f\n", realEvNum, nTracks, imp, planeRot);
          trRd = 0;
          fgets(buf, BFSZ, f19); // read \n
        }
        else // if can't read something like event, skip that line
          fgets(buf, BFSZ, f19);
      }
      else {
        //
        // Read tracks from an event
        //
        fgets(buf, BFSZ, f19);
        fputs(buf, fOut);
        trRd++;
        if (trRd == nTracks)
          readEvent = true;
      }
    }
    fclose(f19);
  }

  fclose(fOut);
  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;
  }
}
