
/*
 *  TEX Device Driver  ver 2.02-
 *  copyright(c) 1988, 1989 by TSG, 1990-93 by SHIMA
 *
 *  err.c :
 *         September 10, 1988 : first edition
 *             April 15, 1989 : second editon
 *                              programed by T.IWAI
 *	very slightly modified against warnings by Oh-Yeah? 25 May 1992
 *	modified for "-wait" option by sempa, 1 Sept 1992
 */

#include <stdio.h>
#include <stdlib.h>
#define _DEF_STDIO_H_
#include <conio.h>
#include <stdarg.h>
#define _DEF_STDARG_H_
#include "dd.h"
#include "err.h"

/* device.c */
void device_end(void);

#if DEBUG & TRACE_LVL
static MODULE main_module =
{"main", NULL};
MODULE *last_module = &main_module;

void module_list_out(void)
{
	MODULE *tmp;

	fprintf(stderr, "(%s", last_module->name);
	for (tmp = last_module->prio; tmp; tmp = tmp->prio)
		fprintf(stderr, "<=%s", tmp->name);
	fprintf(stderr, ")\n\n");
}

#endif

#define HALT   0
#define RETRY  1
#define IGNORE 2

void device_cont(void);
void device_pause(void);

static struct {
	char *msg;
	int recovery;
}

err [] = {
	{
		"No File", RETRY
	}
	,
	{
		"No Memory", HALT
	}
	,
	{
		"Memory Fault", HALT
	}
	,
	{
		"Device Fault", HALT
	}
	,
	{
		"File Fault", HALT
	}
	,
	{
		"Illegal Args", HALT
	}
	,
	{
		"Bad System", IGNORE
	}
	,
	{
		"No Font", RETRY
	}
	,
	{
		"Font Mismatch", HALT
	}
	,
	{
		"Command Error", HALT
	}
	,
	{
		"Unpack Error", HALT
	}
	,
	{
		"Program Stop", HALT
	}
	,
	{
		"Warning", IGNORE
	}
};

BOOL f_wait = TRUE;

void more(void)
{
	int getch();

	if (!f_wait)
		return;
	fprintf(stderr, "\n=== More ===");
	if (getch() == 0x1b) {
		/* ESC key is hit */
		fprintf(stderr, "\n<< BREAK >>\n");
		EXIT(0);
	}
	fprintf(stderr, "\r            \r");
	return;
}

BOOL ask_retry(int mode)
{
	int code;

	device_pause();
	if (!f_wait)
		return FALSE;
	fprintf(stderr, (mode == RETRY) ? "CONTINUE ? (y/n)" : "IGNORE ? (y/n)");
  repeat:						/* */
	if ((code = getch()) == 'y' || code == 'Y') {
		device_cont();
		return (TRUE);
	}
	else if (code == 'n' || code == 'N')
		return (FALSE);
	goto repeat;
}

extern BOOL device_open_flag;

void error(ERROR_NUM error_num, char *message,...)
{
	va_list arg_ptr;

	if (error_num < NO_FILE || error_num > WARNING)
		error_num = PROGRAM_STOP;

	va_start(arg_ptr, message);
	fprintf(stderr, "\n%s: ", err[error_num].msg);
	vfprintf(stderr, message, arg_ptr);
	fprintf(stderr, "\n");

#if DEBUG & TRACE_LVL
	module_list_out();
#endif

	if (err[error_num].recovery != HALT
		&& ask_retry(err[error_num].recovery)) {
		fprintf(stderr, "\n");
		return;
	}
	if (errno == 0)
		errno = 1;

	if (device_open_flag) {
		more();
		device_end();
	}
	EXIT(errno);
}

/* end of file : err.c */
