#include <stdio.h>
#include <stdarg.h>
#include <string.h>

#ifdef WIN32
#define vsnprintf _vsnprintf 
#endif

char *ncpy(char *dst, const char *src, int len)
/*
Copies up (and including) len chars. Terminates with a null char.
So the size of dst should be at least (len+1)
*/
{
        char *xdst = dst;
        int xlen = len;
		if (!dst) return dst;
		if (!src) {
			*dst=0;
			return dst;
		}
/*        for (;(*src !=0) && (len>0); ) {*dst++  = *src++; len--;}*/
        for (;(len>0) && (*src !=0); ) {*dst++  = *src++; len--;}
		/* Changed from previous line by Matt since when len==0, should not try and read memory pointed to be src - BoundsChecker complained*/
        *dst++ = 0;
        xdst[xlen] = 0;
        return xdst;
}


int nvsprintf(char *bf, int count, const char *fmt, va_list argptr )
/*
Same as vsnprintf, but forces null-termination.
So the size of bf should be at least (count+1)
*/
{
	int ret;
	if (!bf) return 0;
	ret=vsnprintf(bf,count,fmt,argptr);
	bf[count]=0;
	return ret;
}

int nsprintf(char *bf, int count, const char * fmt, ...)
/*
Same as snprintf, but forces null-termination.
So the size of bf should be at least (count+1)
*/
{
	int ret;
	va_list args;
	if (!bf) return 0;
	va_start(args,fmt);
	ret=nvsprintf(bf,count,fmt,args);
	va_end(args);
	return ret;
}

char *nstrcat(char *bf, const char *src, int n)
/*
bf should be at least n+1 in size
*/
{
	int l=strlen(bf);
	n-=l;
	bf+=l;
	ncpy(bf,src,n);
	return bf;
}

char *unsafe_strcpy(char *dst, const char *src)
/* wrapper to strcpy in case you really want to use it*/
{
	return strcpy(dst,src);
}

char *unsafe_strncpy(char *dst, const char *src, int n)
/* wrapper to strcpy in case you really want to use it*/
{
	return strncpy(dst,src,n);
}

char *unsafe_strcat(char *dst, const char *src)
/* wrapper to strcat in case you really want to use it*/
{
	return strcat(dst,src);
}

int unsafe_vsprintf(char *bf, const char *fmt, va_list argptr )
/* wrapper to vsprintf in case you really want to use it*/
{
	int ret;
	if (!bf) return 0;
	ret=vsprintf(bf,fmt,argptr);
	return ret;
}

int unsafe_sprintf(char *bf, const char * fmt, ...)
/* wrapper to sprintf in case you really want to use it*/
{
	int ret;
	va_list args;
	if (!bf) return 0;
	va_start(args,fmt);
	ret=unsafe_vsprintf(bf,fmt,args);
	va_end(args);
	return ret;
}

int unsafe_vsnprintf(char *bf, int n, const char *fmt, va_list argptr )
/* wrapper to vsnprintf in case you really want to use it*/
{
	int ret;
	if (!bf) return 0;
	ret=vsnprintf(bf,n,fmt,argptr);
	return ret;
}

int unsafe_snprintf(char *bf, int n, const char * fmt, ...)
/* wrapper to snprintf in case you really want to use it*/
{
	int ret;
	va_list args;
	if (!bf) return 0;
	va_start(args,fmt);
	ret=unsafe_vsnprintf(bf,n,fmt,args);
	va_end(args);
	return ret;
}
