#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <stdarg.h>
#include "lprintf.h"
#include "vsnprintf.h"

void stack_ok(char *whence);
int lprintf( char *buffer, int bfsize, char *format, ... )
{
	int r;
#ifdef SURGEMAIL
	stack_ok(buffer);
#endif
	if (buffer && format && bfsize > 0) {
		va_list arg_list;
		
		va_start(arg_list, format);
		r = vsnprintf( buffer, bfsize, format, arg_list);
		va_end(arg_list);
		if (r<0 || r>=bfsize) buffer[(r = bfsize-1)] = 0;
		return r;
	}
	return -1;
}







/* Works like lprintf, only catenates the string on,
   returning number of chars added or -1 on error.
*/
int lpcat( char *buffer, int bfsize, char *format, ... )
{
	int r;

	if (buffer && format && bfsize > 0) {
		va_list arg_list;
		char *p;
		
		for(p = buffer; --bfsize && *p; p++);
		if (bfsize == 0) return 0;
		/*this takes into account the null such that
		  p[bfsize] is the last character in the buffer*/

		va_start(arg_list, format);
		r = vsnprintf(p, bfsize, format, arg_list);
		if (r >= bfsize) p[bfsize] = 0;
		va_end(arg_list);
		if (r<0) p[bfsize] = 0;
		else return r;
	}
	return -1;
}


#ifdef vsnprintf
#undef vsnprintf
#endif
#ifdef snprintf
#undef snprintf
#endif

int test_vsnprintf(char *str, size_t count, const char *fmt, va_list args)
{
	memset(str,0,count); // wipe as much as possible to cause fault if we can...
#ifdef WIN32
	return _vsnprintf(str,count,fmt,args);
#else
	return vsnprintf(str,count,fmt,args);
#endif
}
int test_snprintf(char *str, size_t count, const char *fmt,...)
{
	int r;
	va_list ap;
	va_start(ap,fmt);
	memset(str,0,count); // wipe as much as possible to cause fault if we can...
#ifdef WIN32
	r =  _vsnprintf(str,count,fmt,ap);
#else
	r = vsnprintf(str,count,fmt,ap);
#endif
	va_end(ap);
	return r;
}
