#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <assert.h>

#include "utils.h"

#define DEBUG 		0
#include "debug.h"

char *make_message(char *fmt, va_list ap_arg) {
	/* modified example from 'man vsprintf' */
	/* Guess we need no more than 150 bytes. */
	int n, size = 150;
	char *p, *np;
	va_list ap;

	assert(fmt != NULL);
	
	va_copy(ap, ap_arg);
	if ((p = malloc (size)) == NULL) {
		perror("make_message: malloc");
		exit(255);
	}
	while (1) {
		/* Try to print in the allocated space. */
		va_copy(ap, ap_arg);
		n = vsnprintf (p, size, fmt, ap);
		va_end(ap);
		/* If that worked, return the string. */
		if (n > -1 && n < size) {
			return p;
		}
		/* Else try again with more space. */
		if (n > -1)	/* glibc 2.1 */
			size = n+1;	/* precisely what is needed */
		else		/* glibc 2.0 */
			size *= 2;	/* twice the old size */
		if ((np = realloc (p, size)) == NULL) {
			perror("make_message: realloc");
			free(p);
			DBG_MSG(1, "make_message: fmt = \"%s\", size = %d", fmt, size);
			exit(255);
		} else {
			p = np;
		}
	}
}

