/*
   File     : log.c
   Author   : Lionel ULMER
   Creation : 07/12/96
*/

#include "global.h"
#include "gui.h" 	/* GuiWriteMessage */


static int infatal = 0;


void fatal(const char *s,...)
{
  va_list ap;

  va_start(ap, s);
  vfprintf(stderr, s, ap);
  fprintf(stderr, "\n");
  va_end(ap);
  if (!infatal) {
    infatal = 1;
    QuitVreng(-1);
  }
}

void warning(const char *s,...)
{
  va_list ap;
#ifndef VRENGD
  char buf[BUFSIZ];
#endif /* !VRENGD */
  
  va_start(ap, s);
#ifndef VRENGD
  if (debug) {
#endif /* !VRENGD */
    vfprintf(stderr, s, ap);
    fprintf(stderr, "\n");
#ifndef VRENGD
  }
  vsprintf(buf, s, ap);
  GuiWriteMessage("warning", NULL, buf);
  vfprintf(stderr, s, ap);
  fprintf(stderr, "\n");
#endif /* !VRENGD */
  va_end(ap);
}

void notice(const char *s,...)
{
#ifndef VRENGD
  va_list ap;
  char buf[BUFSIZ];
  
  va_start(ap, s);
  vsprintf(buf, s, ap);
  GuiWriteMessage("notice", NULL, buf);
  va_end(ap);
#endif /* !VRENGD */
}

void trace(int dbgmask, const char *s,...)
{
  va_list ap;

  if (debug & (1 << dbgmask) || dbgmask == DBG_FORCE) {
    va_start(ap, s);
    vfprintf(stderr, s, ap);
    fprintf(stderr, "\n");
    fflush(stderr);
    va_end(ap);
  }
}

FILE * writelog(const char *s,...)
{
  static FILE *fl = (FILE *) NULL;
#ifndef VRENGD
  va_list ap;
  char logfile[PATH_LEN];

  if (fl == (FILE *) NULL) {
    sprintf(logfile, "%s/log", vrengdir);
    unlink(logfile);
    if ((fl = fopen(logfile, "w")) == NULL) {
      perror("open log");
      return (FILE *) NULL;
    }
  }
  va_start(ap, s);
  vfprintf(fl, s, ap);
  fprintf(fl, "\n");
  va_end(ap);
#endif /* !VRENGD */
  return fl;
}

void closelog(FILE * fl)
{
#ifndef VRENGD
  fclose(fl);
#endif /* !VRENGD */
}

void printlog(void)
{
#ifndef VRENGD
  FILE *fl;
  char logfile[PATH_LEN];
  char buf[BUFSIZ];

  sprintf(logfile, "%s/log", vrengdir);
  if ((fl = fopen(logfile, "r")) == NULL) {
    perror("open log");
    return;
  }
  while (fgets(buf, sizeof(buf), fl) != NULL)
    fputs(buf, stderr);
  closelog(fl);
#endif /* !VRENGD */
}
