/* error.c */

#include "main.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 (tag);

    va_start (list, tag);
    vsprintf (err.errmess, format, list);

    err.errnum = 1;
    return &err;
}


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

void error_box (error *e)
{
    char *tag = "TaskName";
    char *taskname = message_lookup (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, I0|I1|I2, e, BIT(4), taskname);
}
    

/*
 * 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 (tag);
    if (taskname == tag)
        taskname = "ResEd";                  /* desperate */

    if (e)
        _swi (Wimp_ReportError, I0|I1|I2, e, 0, taskname);

    _swi (Wimp_CloseDown, 0);

    dprintf("\nDEAD\n");

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