/* 
   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 <stdlib.h>
#include <time.h>
#include <wchar.h>
#include <locale.h>
#include "libp.h"

#ifdef __BIG_ENDIAN
#define __swap(x,y)
#else
static void __swap(wchar_t *s, int len)
{
    int i;
    for (i=0; i < len; i++,s++) {
        wchar_t x = *s;
        *s = ((unsigned)x >> 8) + (x << 8);
    }
}
#endif
int _RTL_FUNC vfwprintf(FILE *restrict stream, const wchar_t *restrict format, 
        va_list arglist)
{
	int written=0;
	wchar_t buffer[8192],*p;
	int i = 0;
	while (*format) {
        p = buffer;
		while (*format != '%' && *format != 0 && p < buffer + sizeof(buffer))
			*p++ = *format++;
        __swap(buffer,p-buffer);
      	if (fwrite(buffer,2,p-buffer,stream) != p-buffer)
		    return WEOF;
        written += p-buffer;
		if (*format == '%') {
            if  (*(format+1)) {
                p = buffer;
                format = __wonetostr(buffer,&p,format+1,((char **)arglist+i),&i, &written);
                __swap(buffer,p-buffer);
                if (fwrite(buffer,2,p-buffer,stream) != p-buffer)
		            return EOF;
                written += p-buffer;
            } else
                format++;
        }
	}
	return written;
}
int _RTL_FUNC fwprintf(FILE *restrict stream, const wchar_t *restrict format, ...)
{
	return vfwprintf(stream,format,((char *)&format+sizeof(wchar_t *)));
}