/* A version of sprintf that sets a limit on the size of the final
   string, UP TO MAXSTRING; beyond that, at the moment, we get a
   segmenttation fault; this is because stdio doesn't provide
   the proper support. */

#ifndef VXWORKS_CFG
#include <stdio.h>
#define MAXSTRING	1024
#else
#include <vxWorks.h>
#include <stdioLib.h>
#endif
#include <varargs.h>
#include "../h/cdefs.h"

#ifdef VXWORKS_CFG
static char *vsnpBuf;
static vsnpBufSize;

#ifdef VXWORKS_V5
#define fioFormat fioFormatV
#endif

static vsnpFillBuf(inbuf, n, maxSize)
char *inbuf;
int n, maxSize;
{	
	int bytesLeft;

	bytesLeft = maxSize-vsnpBufSize-1;
	if (bytesLeft <= 0)
	 { return;
	 }
	else
	 { n = MIN(bytesLeft, n);
	 }
	strncpy (vsnpBuf, inbuf, n);
	vsnpBuf += n;
	vsnpBuf[0] = '\0';
	vsnpBufSize += n;
	return (OK);
}
#endif

#ifdef vax

char *vsprintf(str,fmt,rest)
char *str;
char *fmt;
va_list rest;
{
	FILE _strbuf;

	_strbuf._flag = _IOWRT+_IOSTRG;
	_strbuf._ptr = str;
	_strbuf._cnt = 32767;
	_doprnt(fmt,(int *)rest,&_strbuf);
	putc('\0',&_strbuf);
	return(str);
}

int vprintf(fmt, ap)
char *fmt;
va_list ap;
{
	return (_doprnt(fmt, ap, stdout));
}

int vfprintf(fp, fmt, ap)
FILE *fp;
char *fmt;
va_list ap;
{
	return (_doprnt(fmt, ap, fp));
}

#endif
/* These functions are standard on Linux, no need to re-define here */
#ifndef LINUX_CFG
char *vsnprintf(str, size, fmt, ap)
char *str;
int size;
char *fmt;
va_list ap;
{
#ifdef VXWORKS_CFG
	vsnpBuf = str;
	vsnpBufSize = 0;
	fioFormat (fmt, ap, vsnpFillBuf, size);
#else
	char buf[MAXSTRING];
	vsprintf (buf, fmt, ap);
	strncpy (str, buf, size);
#endif
	return(str);
}


char *snprintf(va_alist)
va_dcl
{
	char *str;
	int size;
	char *fmt;
	va_list ap;

	va_start(ap);

	str = va_arg(ap, char*);
	size = va_arg(ap, int);
	fmt = va_arg(ap, char*);
	vsnprintf (str, size, fmt, ap);
	va_end(ap);
	return (str);	
}
#endif
