/*
* Copyright (C) 2007-2008, CompHEP Collaboration
* Author: Alexander Sherstnev 
* ------------------------------------------------------
* $Id$
*
* $Log$
*/
#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"

static void
ShowHelp (void)
{
  fprintf (stdout,
  "\n  Using: mix  {name_of_file_with_events_1} ... {name_of_file_with_events_N} -o {name_of_file_with_lhe_events}\n\n"
  "The program mixes several event files in one file, by default output file name is Mixed.PEV and can be chaged with -o\n");
}

int main (int argc, char** argv)
{
  int i, k;
  int nf, kf;
  int frmt;
  int lenth = 0;
  int first = 1;
  char * names;
  char target[2048];

  strcpy (target, "Mixed.PEV");


  nf = kf = argc - 1;
  if (argc < 2) {
    fprintf(stderr, "mix: Enter names of files with events as parameters. \n");
    fprintf(stderr, "     Default name for output event file is Mixed.PEV and\n");
    fprintf(stderr, "     can be overwritten with the option -o {new_file_name}\n");
    return 1;
  }

  for (i = 1; i <= nf; ++i) {
    if (!strcmp (argv[i], "-help") || !strcmp (argv[i], "--help") || !strcmp (argv[i], "-h")) {
      ShowHelp ();
      return 0;
    }

    if (!strcmp (argv[i], "-o")) {
      strcpy (target, argv[++i]);
      kf -= 2;
    } else {
      int tlenth;
      FILE* inFile = fopen(argv[i], "r");
      if (!inFile) {
        fprintf(stderr,"mix: error! File not found: %s\n", argv[i]);
        return -2;
      } else {
        if (first) {
	  frmt = CheckFormat (inFile);
	  first = 0;
        }
	if (frmt != CheckFormat (inFile)) {
          fprintf(stderr, "mix: error! Different formats in the event files!\n");
          return -3;
        }
        tlenth = strlen (argv[i]);
        if (lenth < tlenth) lenth = tlenth;
      }
      fclose (inFile);
    }
  }

  k = 0;
  names = malloc (nf * lenth * sizeof (char));
  for (i = 1; i <= nf; ++i) {
    if (!strcmp (argv[i], "-o")) {
      ++i;
    } else {
      strcpy (names + k * lenth, argv[i]);
      k++;
    }
  }


  switch (frmt) {
    case 1:
      fprintf (stdout, "mix: format cpyth1 detected in all event files\n");
      mix_format1 (kf, target, names, lenth);
      break;
    case 2:
      fprintf (stdout, "mix: format cpyth2 detected in all event files\n");
      mix_format2 (kf, target, names, lenth);
      break;
    case 4:
      fprintf (stdout, "mix: format lhe detected in all event files\n");
      mix_format_lhef (kf, target, names, lenth);
      break;
    default:
      fprintf(stderr, "Error! Unknown format in event files!\n");
      return 4;
    }
  free (names);
  return 0;
}
