/* 
   Copyright 1994-2003 Free Software Foundation, Inc.

   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Lesser General Public
   License as published by the Free Software Foundation; either
   version 2.1 of the License, or (at your option) any later version.

   This library 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
   Lesser General Public License for more details.

   You should have received a copy of the GNU Lesser General Public
   License along with this library; if not, write to the Free Software
   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 
   USA

   You may contact the author at:

   mailto::camille@bluegrass.net

   or by snail mail at:

   David Lindauer
   850 Washburn Ave Apt 99
   Louisville, KY 40222
*/
#include <Stdarg.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <limits.h>
#include <wchar.h>
#include <locale.h>
#include "libp.h"

#define imin(x,y)  ((x) < 0 ? 0 : ((x) < (y) ? (x) : (y)))

int _RTL_FUNC vsnprintf(char *restrict buf, size_t n,
        const char *restrict format, va_list arglist)
{
	int written=0;
	char buffer[8192],*p;
	int i = 0;
	while (*format) {
        int copied;
        p = buffer;
		while (*format != '%' && *format != 0 && p < buffer + sizeof(buffer))
			*p++ = *format++;
        strncpy(buf,buffer,copied = imin(n - written-1, p - buffer));
        written += p-buffer;
        buf += copied;
		if (*format  == '%') {
            if (*(format+1)) {
                p = buffer;
                format = __onetostr(buffer,&p,format+1,((char **)arglist+i),&i, &written);
                strncpy(buf,buffer,copied = imin(n - written-1, p - buffer));
                written += p-buffer;
                buf += copied;
            } else
                format++;
        }
	}
    *buf = 0;
	return written;
}
int _RTL_FUNC _vsnprintf(char *restrict buf, size_t n,
        const char *restrict format, va_list arglist)
{
	return vsnprintf(buf, n, format, arglist);
}
int _RTL_FUNC snprintf(char *restrict buf, size_t n,
        const char *restrict format, ...)
{
	return vsnprintf(buf,n,format,((char *)&format+sizeof(char *)));
}
int _RTL_FUNC _snprintf(char *restrict buf, size_t n,
        const char *restrict format, ...)
{
	return vsnprintf(buf,n,format,((char *)&format+sizeof(char *)));
}
int _RTL_FUNC vsprintf(char *restrict buffer, const char *restrict format,
                                    va_list arglist)
{
    return vsnprintf(buffer, INT_MAX,format,arglist);
}
int _RTL_FUNC sprintf(char *restrict buffer, const char *restrict format, ...)
{
	return vsnprintf(buffer,INT_MAX,format,(((char *)&format) + sizeof(char *)));
}