/* 
   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 mbrtowc (wchar_t *restrict pwc, const char *restrict s, size_t n, mbstate_t *restrict p)
{
  size_t used = 0;
  unsigned char b;

  if (s == NULL) {
    return mbrtowc(NULL,"",1,p);
  }
  if (p == NULL)
    p = &__getRtlData()->mbrtowc_st;

  if (n <= 0)
    return (size_t)-2; 

  if (p->left == 0) {
    b = (unsigned char)*s++;
    used++;
    if (b < 0x80) {
        if (pwc)
            *pwc = (wchar_t)b;
        return b ? 1 : 0;
    }

	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);
  }
  while (used < n) {
      b = (unsigned char) *s++;
      used++;
      if ((b & 0xc0) != 0x80) {
         errno = EILSEQ ;
         return (size_t) -1;
	  }

	  p->value <<= 6;
	  p->value += b & 0x3f;

	  if (--p->left == 0) {
	      if (pwc != NULL)
    		*pwc = (wchar_t) p->value;
	      return p->value ? used : 0;
	  }
  }

  return (size_t) -2;
}
