/*-*-C-*-*
 * Error handling for ResEd
 */

#include "resed.h"

#include "swicall.h"
#include "wimp.h"


#include <stdarg.h>

static error err = {0, ""};


/*
 * Return error message of the given text.  Should usually use
 * error_lookup instead.
 */

error * error_message (char *format, ...)
{
    va_list list;
    va_start (list, format);
    vsprintf (err.errmess, format, list);
    va_end (list);
    err.errnum = 1;
    return &err;
}


/*
 * Return error message of the given looked-up text
 */

error * error_lookup (char *tag, ...)
{
    va_list list;
    char *format = message_lookup(NULL, tag);
    va_start (list, tag);
    vsprintf (err.errmess, format, list);
    va_end (list);
    err.errnum = 1;
    return &err;
}


/*
 * Display non-fatal WIMP error box
 */

void error_box (error *e)
{
    char *tag = "TaskName";
    char *taskname = message_lookup(NULL, tag);
    if (taskname == tag)
        taskname = "ResEd";                  /* desperate */

    /* If task has not initialised with the Wimp, the following
     * call will just print the error
     */

    swi (Wimp_ReportError,
         R0, e,  R1, BIT(4),  R2, taskname,  END);
}
    

/*
 * Display fatal error and then exit, unless e == NULL, in which
 * case just exit.  If the task wants to do stuff at this
 * point it can use atexit.
 */

void error_exit (error *e)
{
    char *tag = "TaskName";
    char *taskname = message_lookup(NULL, tag);
    if (taskname == tag)
        taskname = "ResEd";                  /* desperate */

    if (e)
        swi (Wimp_ReportError, NONX,         /* if this fails, blow up */
             R0, e,      R1, 0,  R2, taskname,  END);
    block
    {
        swi (Wimp_CloseDown, NONX,  END);
    }

    checkheap(TRUE);
    dprintf("\nDEAD\n");

    exit (e ? e->errnum : 0);
}
