/*
 * SJIS code program copyright (C) 2009 - 2010 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 CharSJISLen(unsigned char c)
{
	if (((c >= 0xe0) && (c <= 0xef)) ||
	    ((c >= 0x81) && (c <= 0x9f))) {
		return 2;
	}

	return 1;
}

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

int SJISLen(char* str)
{
	int	i;
	int	len = 0;
	int	l;
	char	s[3];
		
	for (i = 0; str[i] != 0; i += l) {
		l = GetSJISChar(str+i, s);
		len++;
	}
	return len;
}


void SJIStoupper(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] == 0x82) {
			output[i] = input[i];
			if (input[i+1] == 0) {
				output[i+1] = 0;
				break;
			}
			if (((unsigned char)input[i+1] >= 0x81) 
			  && ((unsigned char)input[i+1] <= 0x9a)) {
				output[i+1] = input[i+1] - (0x81-0x60);
				i++;
			} else {
				output[i+1] = input[i+1];
				i++;
			}
		} else {
			output[i] = input[i];
		}
	}
	output[i] = 0;
}

void SJIStolower(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] == 0x82) {
			output[i] = input[i];
			if (input[i+1] == 0) {
				output[i+1] = 0;
				break;
			}
			if (((unsigned char)input[i+1] >= 0x60) 
			  && ((unsigned char)input[i+1] <= 0x79)) {
				output[i+1] = input[i+1] + (0x81-0x60);
				i++;
			} else {
				output[i+1] = input[i+1];
				i++;
			}
		} else {
			output[i] = input[i];
		}
	}
	output[i] = 0;
}


