u32 gf_utf8_wcstombs(char* dest, size_t len, const unsigned short** srcp)
{
	/*
	* Original code from the GNU UTF-8 Library
	*/
	size_t count;
	const unsigned short * src = *srcp;

	if (dest != NULL) {
		char* destptr = dest;
		for (;; src++) {
			unsigned char c;
			unsigned short wc = *src;
			if (wc < 0x80) {
				if (wc == (wchar_t)'\0') {
					if (len == 0) {
						*srcp = src;
						break;
					}
					*destptr = '\0';
					*srcp = NULL;
					break;
				}
				count = 0;
				c = (unsigned char) wc;
			} else if (wc < 0x800) {
				count = 1;
				c = (unsigned char) ((wc >> 6) | 0xC0);
			} else {
				count = 2;
				c = (unsigned char) ((wc >> 12) | 0xE0);
			}
			if (len <= count) {
				*srcp = src;
				break;
			}
			len -= count+1;
			*destptr++ = c;
			if (count > 0)
				do {
					*destptr++ = (unsigned char)(((wc >> (6 * --count)) & 0x3F) | 0x80);
				} while (count > 0);
		}
		return (u32) (destptr - dest);
	} else {
		/* Ignore dest and len. */
		size_t totalcount = 0;
		for (;; src++) {
			unsigned short wc = *src;
			size_t count;
			if (wc < 0x80) {
				if (wc == (wchar_t)'\0') {
					*srcp = NULL;
					break;
				}
				count = 1;
			} else if (wc < 0x800) {
				count = 2;
			} else {
				count = 3;
			}
			totalcount += count;
		}
		return (u32) totalcount;
	}
}
u32 gf_utf8_wcstombs(char* dest, size_t len, const unsigned short** srcp)
{
	 
	size_t count;
	const unsigned short * src = *srcp;

	if (dest != NULL) {
		char* destptr = dest;
		for (;; src++) {
			unsigned char c;
			unsigned short wc = *src;
			if (wc < 0x80) {
				if (wc == (wchar_t)'\0') {
					if (len == 0) {
						*srcp = src;
						break;
					}
					*destptr = '\0';
					*srcp = NULL;
					break;
				}
				count = 0;
				c = (unsigned char) wc;
			} else if (wc < 0x800) {
				count = 1;
				c = (unsigned char) ((wc >> 6) | 0xC0);
			} else {
				count = 2;
				c = (unsigned char) ((wc >> 12) | 0xE0);
			}
			if (len <= count) {
				*srcp = src;
				break;
			}
			len -= count+1;
			*destptr++ = c;
			if (count > 0)
				do {
					*destptr++ = (unsigned char)(((wc >> (6 * --count)) & 0x3F) | 0x80);
				} while (count > 0);
		}
		return (u32) (destptr - dest);
	} else {
		 
		size_t totalcount = 0;
		for (;; src++) {
			unsigned short wc = *src;
			size_t count;
			if (wc < 0x80) {
				if (wc == (wchar_t)'\0') {
					*srcp = NULL;
					break;
				}
				count = 1;
			} else if (wc < 0x800) {
				count = 2;
			} else {
				count = 3;
			}
			totalcount += count;
		}
		return (u32) totalcount;
	}
}