#include <stdlib.h>
#include <stdio.h>
#include <error.h>
#include <fcntl.h>
#include <time.h>
#include <sys/mman.h>
#include <pthread.h>
#include <sys/types.h>
#include <stdarg.h>

/* Since translators can't write to stdout, FOUT is the default
   output handle for misc. debugging messages.
   FOUT is fopen()ed in main() and fclose()d in go_away().
   The name of the debug file is DEBUGFILENAME.  */
#define DEBUGFILENAME ".out"

static char *progname = NULL;
static FILE *fout = NULL;
static int debuglevel = 0;

void
debuginit (int argc, char* argv[])
{
  progname = argv[0];
  /* open the debug stream FOUT: */
  fout = fopen (DEBUGFILENAME, "w");
  if (! fout)
    {
      perror ("can't open error file");
      exit (0);
    }
}

void
debugend ()
{
  /* close the debug stream if necessary. */
  if (fout)
    {
      fflush (fout);
      fclose (fout);
    }
}

void
debugsetlevel (int l)
{ debuglevel = l; }

void
debuglog (int dlevel, const char *msg, ...)
{
  pthread_mutex_t lock;

  if (debuglevel >= dlevel)
    {
      time_t now = time(NULL);
      struct tm *now_tm = localtime(&now);
      va_list ap;

      pthread_mutex_init (&lock, NULL);
      pthread_mutex_lock (&lock);

      va_start(ap, msg);

      fprintf (fout, "%s [%04d-%02d-%02d %02d:%02d:%02d]: ",
	       progname,
	       now_tm->tm_year+1900, now_tm->tm_mon+1, now_tm->tm_mday,
	       now_tm->tm_hour, now_tm->tm_min, now_tm->tm_sec);
      vfprintf (fout, msg, ap);
      fprintf (fout, "\n");
      fflush (fout);

      va_end(ap);

      pthread_mutex_unlock (&lock);
      pthread_mutex_destroy (&lock);
    }
}
