/* Some standard utility stuff. */

#include "defs.h"
#if STDC_HEADERS
# include <stdarg.h>
#endif
#include "util.h"

char *Progname = NULL;

/* Print a message and exit. */

void fatalerr(const char *str, ...)
{
	va_list ap;

	if (Progname) {
		fprintf(stderr, "%s: ", Progname);
	}
	va_start(ap, str);
	vfprintf(stderr, str, ap);
	va_end(ap);
	fputc('\n', stderr);

	exit(1);
}

/* Just print a message. */

void msg(const char *str, ...)
{
	va_list ap;

	va_start(ap, str);
	vfprintf(stderr, str, ap);
	va_end(ap);
}

/* Allocate some space and return a pointer to it.  See new() in util.h. */

void *new_(size_t s)
{
	void *x;

	if ((x = (void *)malloc(s)) == NULL) {
		fatalerr("can't malloc(%d)", s);
	}

	return x;
}

/* Open a file or exit on failure. */

FILE *fileopen(const char *name, const char *mode)
{
	FILE *f;

	if ((f = fopen(name, mode)) == NULL) {
		fatalerr("can't %s '%s'", *mode == 'r' ? "open" : "write", name);
	}
	return (f);
}

/* Like atoi(), but strings ending in 'K' or 'k' are multiplied by 1024. */

int atoik(char *s)
{
	int i, c;

	i = atoi(s);
	c = s[strlen(s) - 1];
	if (c == 'K' || c == 'k') {
		i *= 1024;
	}
	return i;
}
