/*
** error.c -- main error handling routines
**
** This code is Copyright (c) 2002, by the authors of nmh.  See the
** COPYRIGHT file in the root directory of the nmh distribution for
** complete copyright information.
*/

#include <h/mh.h>
#include <errno.h>
#include <stdarg.h>


/*
** print out error message
*/
void
advise(char *what, char *fmt, ...)
{
	va_list ap;

	va_start(ap, fmt);
	advertise(what, NULL, fmt, ap);
	va_end(ap);
}


/*
** print out error message and exit
*/
void
adios(int status, char *what, char *fmt, ...)
{
	va_list ap;

	va_start(ap, fmt);
	advertise(what, NULL, fmt, ap);
	va_end(ap);
	exit(status);
}


/*
** admonish the user
*/
void
admonish(char *what, char *fmt, ...)
{
	va_list ap;

	va_start(ap, fmt);
	advertise(what, "continuing...", fmt, ap);
	va_end(ap);
}


/*
** main routine for printing error messages.
**
** Until 2011-11-01, this routine used writev(). In order to remove
** ``sexy'' syscalls, in favor for mainstream programming, I removed
** it. But I want to preserve the following comment:
**
**     Use writev() if available, for slightly better performance.
**     Why?  Well, there are a couple of reasons.  Primarily, it
**     gives a smoother output...  More importantly though, it's a
**     sexy syscall()...
**
** advertise() does *not* use writev() anymore, and that's good so.
** -- meillo@marmaro.de
*/
void
advertise(char *what, char *tail, char *fmt, va_list ap)
{
	int  eindex = errno;

	fflush(stdout);
	if (invo_name && *invo_name)
		fprintf(stderr, "%s: ", invo_name);
	vfprintf(stderr, fmt, ap);

	if (what) {
		char *s;

		if (*what)
			fprintf(stderr, " %s: ", what);
		if ((s = strerror(eindex)))
			fprintf(stderr, "%s", s);
		else
			fprintf(stderr, "Error %d", eindex);
	}
	if (tail)
		fprintf(stderr, ", %s", tail);
	fputc('\n', stderr);
}
