#include <unistd.h>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>

#include "evnt_tools.h"
#include "mix_format1.h"
#include "mix_format2.h"
#include "mix_format_lhef.h"

int main(int argc,char** argv)
{
  int i;
  int format;
  int nf = argc - 1;
  int* frmt     = malloc(nf * sizeof(int));
  FILE** inFile = malloc(nf * sizeof(FILE*));
  char ** names;

  if (argc < 2) {
    fprintf(stderr, "Enter names of files with events as parameters. \n");
    return 1;
  }

  names = malloc (nf * sizeof (char*));
  for (i = 0; i < nf; ++i) {
    names[i] = argv[i + 1];
    inFile[i] = fopen(names[i], "r");
    if (!inFile[i]) {
      fprintf(stderr,"Error! File not found: %s\n",names[i]);
      return 2;
    } else {
      frmt[i] = CheckFormat (inFile[i]);
    }
  }

  format = frmt[0];
  for (i = 0; i < nf; ++i) {
    frmt[i] -= format;
    if (frmt[i]) {
      fprintf(stderr, "Error! Different formats in th eevent files!\n");
      return 3;
    }
  }

  switch (format) {
    case 1:
      mix_format1 (nf, names);
      break;
    case 2:
      mix_format2 (nf, names);
      break;
    case 3:
      mix_format_lhef (nf, names);
      break;
    default:
      fprintf(stderr, "Error! Unknow format in event files!\n");
      return 4;
    }

  free (inFile);
  free (frmt);
  return 0;
}
