#error By license you aren't permitted to compile this.  Read GUISpell.doc.
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include <proto/dos.h>
#include "error.h"

static void (*CleanupCode)(void);

static void PrintMessage (char **code)
{
  struct DosLibrary *DOSBase = (struct DosLibrary *) OpenLibrary (DOSNAME, 0);

  if (DOSBase)
    {
      if (Output ())
        {
	  va_list ap;
	  char *string;
	  int number;
	  char buffer[(sizeof (int)) * 4];
	  int i;

	  va_start (ap, *code);
	  while (**code)
            switch (**code)
	      {
	      case 'd':
	        number = va_arg (ap, int);
	        buffer[15] = '\0';
	        buffer[14] = '0';
	        for (i = 14; number; i--)
	          buffer[i] = number % 10 + '0', number /= 10;
	        string = &buffer[++i];
	        goto write_error;
	      case 's':
	        string = va_arg (ap, char *);
	      write_error:
                Write (Output (), string, strlen (string));
	        (*code)++;
	        break;
	      default:
	        **code = '\0';
	      }
          va_end (ap);
        }
      CloseLibrary ((struct Library *) DOSBase);
    }
}

void Warning (char *code, ...)
{
  PrintMessage (&code);
}

void Error (char *code, ...)
{
  PrintMessage (&code);
  if (CleanupCode)
    (*CleanupCode) ();
  exit (EXIT_FAILURE);
}

void OnError (void (*f)(void))
{
  CleanupCode = f;
}
