/*
 * EUC code program copyright (C) 2009 - 2013 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.h>

#include <string>
#include <complex>

#include "syserr.h"

#include "bin_node.h"

int CharEUCLen(unsigned char c)
{
	if (c == 0x8f) {
		return 3;
	} else if (c >= 0xa1) {
		return 2;
	}

	return 1;
}

static int GetEUCChar(char* str, char* s1)
{
	int i;	
	int n = CharEUCLen(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* EUCChar(char* str)
{
	Node*	nd = Nil;
	Node*	n = Nil;
	int	i;
	int	l;
	char	s[4];
	
	for (i = 0; str[i] != 0; i += l) {
		l = GetEUCChar(str+i, s);
		n = MkList(new Atom(s));
		nd = Append(nd, n);
	}
	return nd;
}

int EUCLen(char* str)
{
	int	i;
	int	len = 0;
	int	l;
	char	s[4];
		
	for (i = 0; str[i] != 0; i += l) {
		l = GetEUCChar(str+i, s);
		len++;
	}
	return len;
}

void EUCtoupper(char* input, char* output)
{
	int	i;
	int	c;
	int	n;
	
	for (i = 0; i < strlen(input); i++) {
		if ((unsigned char)input[i] < 0x80) {
			output[i] = toupper(input[i]);
		} else if ((unsigned char)input[i] == 0xa3) {
			output[i] = input[i];
			if (input[i+1] == 0) {
				output[i+1] = 0;
				break;
			}
			if (((unsigned char)input[i+1] >= 0xe1) 
			  && ((unsigned char)input[i+1] <= 0xfa)) {
				output[i+1] = input[i+1] - (0xe1-0xc1);
				i++;
			} else {
				output[i+1] = input[i+1];
				i++;
			}
		} else {
			output[i] = input[i];
		}
	}
	output[i] = 0;
}

void EUCtolower(char* input, char* output)
{
	int	i;
	int	c;
	int	n;
	
	for (i = 0; i < strlen(input); i++) {
		if ((unsigned char)input[i] < 0x80) {
			output[i] = tolower(input[i]);
		} else if ((unsigned char)input[i] == 0xa3) {
			output[i] = input[i];
			if (input[i+1] == 0) {
				output[i+1] = 0;
				break;
			}
			if (((unsigned char)input[i+1] >= 0xc1) 
			  && ((unsigned char)input[i+1] <= 0xda)) {
				output[i+1] = input[i+1] + (0xe1-0xc1);
				i++;
			} else {
				output[i+1] = input[i+1];
				i++;
			}
		} else {
			output[i] = input[i];
		}
	}
	output[i] = 0;
}

