#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

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

int _ExitOnError = 1; // If set to 1, exit on error
int _Verbose = 1;     // If set to 1, errors are reported
int _Debug = 0;       // If set to 1, debugging

/* If we're not using GNU C, elide __attribute__ */
#if !defined __GNUC__ && !defined __attribute__
#define __attribute__(x) /*NOTHING*/
#endif

void SysError_(const char *caller, const char *fmt, ...) __attribute__((noreturn));

void
SysError_(const char *caller, const char *fmt, ...)
{
  va_list args;
  int saved_errno = errno;

  va_start(args, fmt);

  printf("\n");
  fprintf(stderr, "%s  error (%s): ", PACKAGE_NAME, caller);
  vfprintf(stderr, fmt, args);
  fprintf(stderr, "\n");

  va_end(args);

  if (saved_errno)
    {
      errno = saved_errno;
      perror("System error message");
    }

  exit(EXIT_FAILURE);
}

void
Error_(const char *caller, const char *fmt, ...)
{
  va_list args;

  va_start(args, fmt);

  printf("\n");
  fprintf(stderr, "%s  error (%s): ", PACKAGE_NAME, caller);
  vfprintf(stderr, fmt, args);
  fprintf(stderr, "\n");

  va_end(args);

  if (_ExitOnError) exit(EXIT_FAILURE);
}

void
Warning_(const char *caller, const char *fmt, ...)
{
  va_list args;

  va_start(args, fmt);

  if (_Verbose)
    {
      fprintf(stderr, "%s  warning (%s): ", PACKAGE_NAME, caller);
      vfprintf(stderr, fmt, args);
      fprintf(stderr, "\n");
    }

  va_end(args);
}

void
Message_(const char *caller, const char *fmt, ...)
{
  va_list args;

  va_start(args, fmt);

  fprintf(stdout, "%s  %-18s: ", PACKAGE_NAME, caller);
  vfprintf(stdout, fmt, args);
  fprintf(stdout, "\n");

  va_end(args);
}
