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

#include "resed.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(&msgs, 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(&msgs, tag);
    if (taskname == tag)
        taskname = ICONNAME;                 /* fallback */

    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.
 */

void error_exit (error *e)
{
    char *tag = "TaskName";
    char *taskname = message_lookup(&msgs, tag);
    if (taskname == tag)
        taskname = ICONNAME;                 /* fallback */

    if (wimpstarted)
    {
        if (e)
            swi (Wimp_ReportError, NONX,             /* if this fails, blow up */
                 R0, e,  R1, 0,  R2, taskname,  END);
        document_free_all ();
        checkheap(TRUE);

        block
        {
            int task;
            strncpy((char *)&task, "TASK", 4);
            swi (Wimp_CloseDown, NONX, R0,  taskhandle,  R1, task,  END);
        }
    }
    else
    {
        if (e)
            fprintf (stderr, "%s: %s\n", taskname, e->errmess);
/*          swi (OS_GenerateError, NONX, R0, e, END); */
    }
dprintf("\nWE'RE GONE");
    exit (e ? e->errnum : 0);
}
