/*
 * UTF8 code program copyright (C) 2009 H.Niwa
 */

/*
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2, or (at your option)
 * any later version.

 * This program 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 General Public License for more details.

 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
 * 02110-1301, USA.
 */

#include "config.h"

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>

#include <string>

#include "syserr.h"

#include "bin_node.h"


int CharUTF8Len(unsigned char c)
{
	if (c >= 0xfc) {
		return 6;
	} else if (c >= 0xf8) {
		return 5;
	} else if (c >= 0xf0) {
		return 4;
	} else if (c >= 0xe0) {
		return 3;
	} else if (c >= 0xc0) {
		return 2;
	}

	return 1;
}

static int GetUTF8Char(char* str, char* s1)
{
	int i;	
	int n = CharUTF8Len(str[0]);

	if (n == 0) {
		s1[0] = 0;
		return 0;
	}
	
	for (i = 0; i < n; i++) {
		if (str[i] == 0) {
			break;
		}
		s1[i] = str[i];
	}
	s1[i] = 0;

	return n;
}

Node* UTF8Char(char* str)
{
	Node*	nd = Nil;
	Node*	n = Nil;
	int	i;
	int	l;
	char	s[7];
	
	for (i = 0; str[i] != 0; i += l) {
		l = GetUTF8Char(str+i, s);
		n = MkList(new Atom(s));
		nd = Append(nd, n);
	}
	return nd;
}

int UTF8Len(char* str)
{
	int	i;
	int	len = 0;
	int	l;
	char	s[7];
		
	for (i = 0; str[i] != 0; i += l) {
		l = GetUTF8Char(str+i, s);
		len++;
	}
	return len;
}
