#include "my-lib.h"

#include <values.h>

void
die(char *fmt, ...)
{
	va_list	args;

	fflush(stdout);
	va_start(args, fmt);
	vfprintf(stderr, fmt, args);
	va_end(args);
	fprintf(stderr, "\n");
	exit(1);
}

void asfail(char *file, int line, char *prop)
{
	fflush(stdout);
	fprintf(stderr, "%s %d: assert(%s) failed.\n", file, line, prop);
	abort();
}


/* safe version of fopen */
#if defined(_WIN32)
FILE *safeopen(char *fileName, char *mode) {
#else
FILE *sopen(char *fileName, char *mode) {
#endif
	FILE *file;
	
	if ((file = fopen((char*)fileName, mode)) == NULL)
		die("sopen unable to open file");
	
	return file;
}

/* safe version of fwrite */
void swrite(void *ptr, size_t size, size_t nmemb, FILE *file) {
	size_t bytes = size * nmemb;
	
	if (0 == bytes) return;
	
	unless (1 == fwrite(ptr, size * nmemb, 1, file))
		die("swrite failed");
}

void swriteUint(uint n, FILE *file) {
	swrite(&n, sizeof(uint), 1, file);
}

void sread(void *ptr, size_t size, size_t nmemb, FILE *file) {
	unless (1 == fread(ptr, size * nmemb, 1, file))
		die("sread failed");
}

uint sreadUint(FILE *file) {
	uint n;

	sread(&n, sizeof(uint), 1, file);

	return n;
}

/* ------------------------------------------------- */
/*                 intToCommaString                  */
/* ------------------------------------------------- */
/* BUF_SIZE must be == 1 mod 4 so that the ',' is inserted in the right place */
#define BUF_SIZE 81

string intToCommaString(int n) {
	static char buf[BUF_SIZE];
	int i;
	
	i = BUF_SIZE - 1;
	buf[i--] = '\000';
	
	if (0 == n)
		buf[i--] = '0';
#if defined(_WIN32)
// FIXME: ...
#define MININT (-2147483647 - 1)
#endif
 	else if (MININT == n) {
		/* must treat MININT specially, because I negate stuff later */
		strcpy(buf + 1, "-2,147,483,648");
		i = 0;
	} else {
		int m;
	
 		if (n > 0) m = n; else m = -n;
	
		while (m > 0) {
 			buf[i--] = m % 10 + '0';
			m = m / 10;
 			if (i % 4 == 0 and m > 0) buf[i--] = ',';
 		}
 		if (n < 0) buf[i--] = '-';
 	}
 	return buf + i + 1;
}

string uintToCommaString(uint n) {
	static char buf[BUF_SIZE];
	int i;
	
	i = BUF_SIZE - 1;
	buf[i--] = '\000';
	
	if (0 == n)
		buf[i--] = '0';
        else {
		while (n > 0) {
 			buf[i--] = n % 10 + '0';
			n = n / 10;
 			if (i % 4 == 0 and n > 0) buf[i--] = ',';
 		}
 	}
 	return buf + i + 1;
}

string ullongToCommaString(ullong n) {
	static char buf[BUF_SIZE];
	int i;
	
	i = BUF_SIZE - 1;
	buf[i--] = '\000';
	
	if (0 == n)
		buf[i--] = '0';
        else {
		while (n > 0) {
 			buf[i--] = n % 10 + '0';
			n = n / 10;
 			if (i % 4 == 0 and n > 0) buf[i--] = ',';
 		}
 	}
 	return buf + i + 1;
}

