/* Copyright (C) 2003, CompHEP Collaboration
 * Author: Alexander Sherstnev
 *----------------------------------------------
 *
 * $Id: tag_writer.c,v 1.4 2003/11/01 21:45:32 kryukov Exp $
 *
 * $Log: tag_writer.c,v $
 * Revision 1.4  2003/11/01 21:45:32  kryukov
 * Copyright record
 *
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include "tag_reader.h"
#include "tag_parser.h"
#include "tag_writer.h"

FILE *evfile;

int
tag_writer (FILE * file, elementary_tag * tag)
{
  int i, k;
  int len;

  if (ftell (file))
    fputc ('\n', file);
  fprintf (file, "##%s:", tag->tagname);
  len = strlen (tag->tagname);
  for (i = 0; i < tag->tagsize; i++)
    {
      fprintf (file, " %s,", tag->commands[i]);
      if (!((i + 1) % 5) && i != tag->tagsize - 1)
	{
	  fprintf (file, "\n");
	  for (k = 0; k < len + 3; k++)
	    {
	      fputc (' ', file);
	    }
	}
    }
  fprintf (file, ";");
  return 0;
}


int
cap_writer (FILE * file, tags * p)
{
  int i;

  for (i = 0; i < p->number_of_tags; i++)
    tag_writer (file, p->tag[i]);
  fprintf (file, ";\n");
  return 0;
}

int
change_cap (tags * t, int nEvents, double mult, double rmax, double cs, double er)
{
  int n;
  int N, Nold;
  double maxW, ml, old_ml;
  string_comnd com;

  n = get_tag (0, t, "total");
  if (n != -1)
    {
      Nold = get_ival (0, "Nevent", t->tag[n]);
      N = nEvents + Nold;
      strcpy (com.name, "Nevent");
      change_ival (N, 8 - intlen (N), com, t->tag[n]);
      strcpy (com.name, "CrosSec");
      change_fval (cs, com, t->tag[n]);
      strcpy (com.name, "CrosSecErr");
      change_fval (er, com, t->tag[n]);
    }
  else
    {
      fprintf (stderr, "***Error! The total tag has not been found...\n");
      return -1;
    }

  n = get_tag (0, t, "process");
  if (n != -1)
    {
      strcpy (com.name, "CrosSec");
      change_fval (cs, com, t->tag[n]);
      strcpy (com.name, "CrosSecErr");
      change_fval (er, com, t->tag[n]);
    }
  else
    {
      fprintf (stderr, "***Error! The process tag has not been found...\n");
      return -1;
    }

  n = get_tag (0, t, "n_event");
  if (n != -1)
    {
      strcpy (com.name, "N");
      change_ival (N, 8 - intlen (N), com, t->tag[n]);
      old_ml = get_fval (0, "mult", t->tag[n]);
      ml = (old_ml * (double) Nold + mult * (double) nEvents) / N;
      strcpy (com.name, "mult");
      change_fval (ml, com, t->tag[n]);
      maxW = get_ival (0, "maxW", t->tag[n]);
      strcpy (com.name, "maxW");
      if (maxW < rmax)
	change_fval (rmax, com, t->tag[n]);
    }
  else
    {
      fprintf (stderr, "***Error! The n_event tag has not been found...\n");
      return -1;
    }
  return 0;
}
