/**********************************************************************
 
	Copyright (C) 2003 Hirohisa MORI <joshua@nichibun.ac.jp>
 
	This program is free software; you can redistribute it 
	and/or modify it under the terms of the GLOBALBASE 
	Library General Public License (G-LGPL) as published by 

	http://www.globalbase.org/
 
	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.

**********************************************************************/


#include	<stdlib.h>
#include	"memory_debug.h"
#include	"long_char.h"

typedef struct euc_work {
	unsigned char	buf;
} EUC_WORK;

void * open_euc();
int close_euc(unsigned char *,void *);
int euc2int(L_CHAR *,void*,unsigned char);
int int2euc(unsigned char *,void*,L_CHAR);

CODE_METHOD euc_cm = {
	"EUC-JP",
	LCC_EUC_JP,
	0,
	2,
	0,
	{0,0},
	open_euc,
	close_euc,
	euc2int,
	int2euc,
	0
};


void *
open_euc()
{
EUC_WORK * ret;
	ret = d_alloc(sizeof(EUC_WORK));
	ret->buf = 0;
	return ret;
}

int
close_euc(unsigned char * ret,void * work)
{
	d_f_ree(work);
	return 0;
}

int
euc2int(L_CHAR * ret,void * _work,unsigned char ch)
{
unsigned int euc;
EUC_WORK * work;

	work = (EUC_WORK*)_work;
	if ( work->buf == 0 ) {
		if ( ch & 0x80 ) {
			work->buf = ch;
			return 0;
		}
		else {
			*ret = ((int)ch)&0x0ff;
			return 1;
		}
	}
	else {
		euc = ((work->buf)<<8)|ch;
		if ((euc & 0xff00) == 0x8e00)
        		*ret = hankaku2zenkaku(euc & 0xff);
		else	*ret = (euc & ~0x8080)|LCZ_2BC_JISX0208_1990;
		work->buf = 0;
		return 1;
	}
}

int
int2euc(unsigned char * ret,void * _work,L_CHAR ch)
{
	if ( (ch&LCZM_1B_TYPE) == LCZ_1BC_ASCII ) {
		if ( ch & 0x80 )
			return 0;
		ret[0] = ch&0xff;
		return 1;
	}
	if ( (ch&LCZM_2B_TYPE) == LCZ_2BC_JISX0208_1990 ) {
		ret[0] = ((ch>>8)&0xff)|0x80;
		ret[1] = (ch&0xff)|0x80;
		return 2;
	}
	return 0;
}
