#include <stdio.h>
#include "ime.h"

int is_valid_code(int encode, unsigned char *int_code, int code_len)
{
	unsigned char code0, code1, code2, code3;
	
	code0 = int_code[0];
	code1 = int_code[1];

	switch (encode) {
		case ENCODE_GB2312:
			if (code0 < 0xA1 || code0 > 0xFE)
				return (-1);
			if (code1 < 0xA1 || code1 > 0xFE)
				return (-1);
			break;
			
		case ENCODE_GBK:
			if (code0 < 0x81 || code0 > 0xFE)
				return (-1);
			if (code1 < 0x40 || code1 > 0xFE || code1 == 0x7F)
				return (-1);
			break;

		case ENCODE_GB18030:
			if (code_len == 2) {
				if (code0 < 0x81 || code0 > 0xFE)
					return (-1);
				if (code1 < 0x40 || code1 > 0xFE || code1 == 0x7F)
					return (-1);
			} else if (code_len == 4) {
				code2 = int_code[2];
				code3 = int_code[3];
				if (code0 < 0x81 || code0 > 0xFE)
					return (-1);
				if (code1 < 0x30 || code1 > 0x39)
					return (-1);
				if (code2 < 0x81 || code2 > 0xFE)
					return (-1);
				if (code3 < 0x30 || code3 > 0x39)
					return (-1);
			}
			break;

		case ENCODE_BIG5:
			if (code0 < 0xA1 || code0 > 0xFE)
				return (-1);
			if (code1 < 0x40 || code1 > 0xFE)
				return (-1);
			if (code1 > 0x7E && code1 < 0xA1)
				return (-1);
			break;

		case ENCODE_EUCTW:
			if (code_len == 2) {
				if (code0 < 0x80 || code1 <0x80)
					return (-1);
			} if (code_len == 4) {
				code2 = int_code[2];
				code3 = int_code[3];
				if (code0 != 0x8E)
					return(-1);
				if (code1 < 0x80 || code2 < 0x80 || code3 < 0x80)
					return(-1);
			}
			break;

		case ENCODE_BIG5HKSCS:
			if (code0 < 0x81 || code0 > 0xFE)
				return (-1);
			if (code1 < 0x40 || code1 > 0xFE)
				return (-1);
			break;

		case ENCODE_UTF8:
			break;
	}
	return(0);
}
