/* error.c -- error handler for interactive utilities
   Copyright (C) 2014 Ron Charlton
   Copyright (C) 1990, 91, 92, 93, 94 Free Software Foundation, Inc.

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 2, or (at your option)
   any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.  */

/* Written by David MacKenzie <djm@gnu.ai.mit.edu>.  */

/* Modified 2014-02-16 by Ron Charlton to use progName instead of program_name.
 * Also show how to call the danged thing.  Whitespace reformatted.  Use
 * block statements for if(){}.  Cleaned up for use with Windows cl.exe
 * compilers.
 *
 * Usage:
 *	error(int status, int errnum, const char *message, ...)
 *	status   - exit status (EXIT_FAILURE or equivalent status)
 *	errnum   - if non-zero, strerror(errnum) is printed
 *	message  - like printf() format string
 *	...      - list of printf() style arguments used with the format string
 */
char RCS_ID[] = "$Id: error.c 1.14 2015-06-18 17:16:27-04 Ron Exp $";

#include <stdarg.h>		// for va_list, va_start(), vfprintf(), va_end()
#include <stdio.h>
#include <stdlib.h>
#include <string.h>		// for strerror()

#include "error.h"

#ifdef __cplusplus
extern "C" {
#endif

/*  The calling program should define char *progName and set it to the
	name of the executing program.

	THE CALLING PROGRAM *MUST* DEFINE progName as 'char *progName = "blah";'
	OR CALLING error() WILL CAUSE A CRASH.
	DO NOT USE 'char progName[] = "blah";'.  If you do, CRASH.
 */

extern char *progName;

/* Print the program name and error message MESSAGE, which is a printf-style
   format string with optional args.
   If ERRNUM is nonzero, print its corresponding system error message.
   Exit with status STATUS if it is nonzero.  */
void
error(int status, int errnum, const char *message, ...)
{
	va_list args;

	fflush(stdout);
	fprintf(stderr, "%s: ", progName);

	va_start(args, message);
	vfprintf(stderr, message, args);
	va_end(args);

	if (errnum) {
		fprintf(stderr, ": %s", strerror(errnum));
	}

	putc('\n', stderr);

	fflush(stderr);

	if (status) {
		exit(status);
	}
}

#ifdef __cplusplus
}
#endif
