// util.c, Peter McGavin, 1 July 2002

// public domain

#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>

#include "util.h"

/**********************************************************************/
#ifdef DEBUG
static FILE *f = NULL;
#endif

/**********************************************************************/
#ifdef DEBUG
static void open_log (void)
{
  if ((f = fopen ("/dev/tty", "w")) == NULL) {
    fprintf (stderr, "Can't open logfile\n");
    exit (EXIT_FAILURE);
  }
}
#endif

/**********************************************************************/
void error (char *msg, ...)
{
  va_list argptr;

#ifdef DEBUG
  open_log ();
  fprintf (f, "Error: ");
#endif
  printf ("telluser ");
  va_start (argptr, msg);
#ifdef DEBUG
  vfprintf (f, msg, argptr);
#endif
  vprintf (msg, argptr);
  va_end (argptr);
#ifdef DEBUG
  fprintf (f, "\n");
  fflush (f);
#endif
  printf ("\n");
  fflush (stdout);
}

/**********************************************************************/
void debug (char *msg, ...)
{
#ifdef DEBUG
  va_list argptr;

  open_log ();
  va_start (argptr, msg);
  vfprintf (f, msg, argptr);
  va_end (argptr);
  fflush (f);
#endif
}

/**********************************************************************/
void fatal (char *msg, ...)
{
  va_list argptr;

#ifdef DEBUG
  open_log ();
  fprintf (f, "Fatal error: ");
#endif
  fprintf (stderr, "Fatal error: ");
  printf ("tellusererror ");
  va_start (argptr, msg);
#ifdef DEBUG
  vfprintf (f, msg, argptr);
#endif
  vfprintf (stderr, msg, argptr);
  vprintf (msg, argptr);
  va_end (argptr);
#ifdef DEBUG
  fprintf (f, "\n");
  fflush (f);
#endif
  fprintf (stderr, "\n");
  printf ("\n");
  fflush (stdout);
  exit (EXIT_FAILURE);
}

/**********************************************************************/
