/*
    This file is part of xmms-curses, copyright 2003-2005 Knut Auvor Grythe.

    xmms-curses 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 of the License, or
    (at your option) any later version.

    xmms-curses 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 xmms-curses; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*/

#include <stdio.h>
#include <stdlib.h>
#include <glib.h>
#include <glib/gstdio.h>
#include <ncursesw/curses.h>

gchar *make_message(const gchar *fmt, va_list ap)
{
	/* Guess we need no more than 100 bytes. */
	gint n, size = 100;
	gchar *p;
	//va_list ap;
	if ((p = malloc (size)) == NULL)
		return NULL;
	while (1) {
		/* Try to print in the allocated space. */
		//va_start(ap, fmt);
		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 ((p = realloc (p, size)) == NULL)
			return NULL;
	}
}

gint waddstrf(WINDOW *win, const gchar *fmt, ...)
{
	gint retval;
	va_list ap;
	va_start(ap, fmt);
	gchar *message = make_message(fmt, ap);
	va_end(ap);
	retval = waddstr(win, message);
	g_free(message);
	return retval;
}

gint mvwaddstrf(WINDOW *win, gint y, gint x, const gchar *fmt, ...)
{
	gint retval;
	va_list ap;
	va_start(ap, fmt);
	gchar *message = make_message(fmt, ap);
	va_end(ap);
	retval = mvwaddstr(win, y, x, message);
	g_free(message);
	return retval;
}

gint waddnstrf(WINDOW *win, const gchar *fmt, gint n, ...)
{
	int retval;
	va_list ap;
	va_start(ap, n);
	gchar *message = make_message(fmt, ap);
	va_end(ap);
	retval = waddnstr(win, message, n);
	g_free(message);
	return retval;
}

gint mvwaddnstrf(WINDOW *win, gint y, gint x, const gchar *fmt, gint n, ...)
{
	gint retval;
	va_list ap;
	va_start(ap, n);
	gchar *message = make_message(fmt, ap);
	va_end(ap);
	retval = mvwaddnstr(win, y, x, message, n);
	g_free(message);
	return retval;
}
