/****************************************************************************/
/*	Copyright (c) 2009, Bendor Research Pty. Ltd. All rights reserved.		*/
/*	This software is released under the GNU General Public License, version	*/
/*	3, with the exemptions that 1) the header files installed by this 	 	*/
/*	package can be included in closed-source code and 2) the libraries		*/
/*	built by this package can be statically linked into a closed-source 	*/
/*	binary. See the file LICENSE for the details.							*/
/*	This software is provided "AS IS", without any warranty or guarantee.	*/
/*	By using this software you acknowledge that neither Bendor Research nor	*/
/*	any of its personnel or affiliates can be held liable for any damages,	*/
/*	including, but not limited to, loss of business, loss of money, loss of */
/*	life, loss of reputation, arising out of this software being faulty or	*/
/*	not performing as advertised, even if Bendor Research was aware of such	*/
/*	faults in the software. You use this software at your own risk, any and */
/*	all liabilities that arise out of your using this software are strictly	*/
/*	yours.																	*/
/****************************************************************************/

#include <wchar.h>

/*
*	Converts a UTF-8 sequence to an unsigned short
*	~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*	Does not check for RFC3629 conformance
*/

int		mbtowc( unsigned short *wc, const char *mb, size_t n )
{
wchar_t			wide;
unsigned long	next, mask, patt;
unsigned int	bnum;

	if ( ! mb ) return( 0 );
	if ( ! n ) return( -1 );

	if ( ! ( next = *mb++ & 255 ) ) return( 0 );

	if ( ( next & 0x80 ) == 0x00 ) {

		if ( wc ) *wc = next;
		return( 1 );
	}

	mask = 0xe0;
	patt = 0xc0;
	bnum = 2;

	for ( ;; ) {

		if ( bnum >= n || bnum ==  ) {

			// Can't possibly have enough chars

			return( -1 );
		}

		if ( ( next & mask ) == patt ) break;

		mask = ( mask >> 1 ) | 0x80;
		patt = ( patt >> 1 ) | 0x80;
		bnum++;
	}

	// We found a start match and we have enough characters

	wide = next & ~mask;
	n    = bnum + 1;

	while ( bnum-- ) {

		if ( ( ( next = *mb++ & 255 ) & 0xc0 ) != 0x80 ) {

			// The character is not valid

			return( -1 );
		}

		wide = ( wide << 6 ) | ( next & 0x3f );
	}

	if ( _BLC_CONFIG_RFC3629 ) {

		if ( (unsigned long) wide >= 0x110000ul ) return( -1 );
		if ( (unsigned long) wide >= 0xd800u &&
			 (unsigned long) wide <= 0xe000u ) return( -1 );

		switch ( n ) {

			case 1: 	break;
			case 2: 	if ( (unsigned long) wide >= 0x80 ) break;
			case 3: 	if ( (unsigned long) wide >= 0x800 )  break;
			case 4: 	if ( (unsigned long) wide >= 0x10000ul ) break;
			default:	return( -1 );
		}
	}

	if ( wc ) *wc = wide;
	return( n );
}

/** @} */

