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

size_t mbsrtowcs (wchar_t *restrict dst, const char **restrict src, size_t len, mbstate_t *restrict p)
{
  unsigned char b;
  size_t used = 0;
  const char *r = *src;

  if (!p)
    p = &__getRtlData()->mbsrtowcs_st;

  if (dst == NULL)
    len = (size_t)-1;

  while (used < len) {
    b = (unsigned char)*r++;
    if (p->left) {
        if ((b & 0xc0) != 0x80) {
            errno = EILSEQ;
            return (size_t)-1;
        }
        p->value <<=6;
        p->value |= b & 0x3f;
        if (!--p->left) {
            if (dst)
                *dst++ = p->value;
            if (p->value == L'\0') {
                *src = NULL;
                return used;
            }
            used++;
        }
    } else {
        if (b < 0x80) {
            if (dst)
                *dst++ = (wchar_t)b;
            if (b == L'\0') {
                *src = NULL;
                return used;
            }
            used++;
        } else {
	        if ((b & 0xc0) == 0x80 || b == 0xfe || b == 0xff) {
                errno = EILSEQ ;
                return (size_t) -1;
            }
            b <<= 1;
            while (b & 0x80) {
                p->left++ ;
                b <<= 1;
            }
            p->value = b >> (p->left + 1);
        }
    }
  }

  *src = r;

  return used;
}
