/*
Copyright 1990-2001 Sun Microsystems, Inc. All Rights Reserved.

Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions: The above copyright notice and this
permission notice shall be included in all copies or substantial
portions of the Software.


THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE OPEN GROUP OR SUN MICROSYSTEMS, INC. BE LIABLE
FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH
THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE EVEN IF
ADVISED IN ADVANCE OF THE POSSIBILITY OF SUCH DAMAGES.


Except as contained in this notice, the names of The Open Group and/or
Sun Microsystems, Inc. shall not be used in advertising or otherwise to
promote the sale, use or other dealings in this Software without prior
written authorization from The Open Group and/or Sun Microsystems,
Inc., as applicable.


X Window System is a trademark of The Open Group

OSF/1, OSF/Motif and Motif are registered trademarks, and OSF, the OSF
logo, LBX, X Window System, and Xinerama are trademarks of the Open
Group. All other trademarks and registered trademarks mentioned herein
are the property of their respective owners. No right, title or
interest in or to any trademark, service mark, logo or trade name of
Sun Microsystems, Inc. or its licensors is granted.

*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include "CodeTable.h"
#include "UDEngine.h"

#define MAXBUF		(1024 * 1024)
#define MAXLEN		256
#define MAXTAB		0x00018000
#define OFFSET_START 	1

#define CODETABLE_ID	"<codetable>"
#define KEYTABLE_ID	"<preedit_keytable>"
#define CTINFO_ID	"<codetable_info>"

enum	_READING { 
	CODETABLE, KEYTABLE, CTINFO, OTHER 
};

typedef struct {
	char	key[12];
	char	*code;
} key_table;

char	*code_data = NULL, *p_code = NULL;		/* code table data buffer */

char    name[16], locale[16], wildchar;

key_table 	*k_tab = NULL;
table_index 	tab_idx[MAXIDX];
int	tablen = 0; 			/* code table length */
int	max_len = 0; 			/* Maximum keystroke length */

int write_code_table(engine_info *im, table_index*, code_table*, int, char *, int);

int make_code_table(engine_info *im, char * in_file)
{
	FILE	*in_fp;
	int	fd;
	int	tabcomp();
	code_table	*c_tab = NULL;
	int	i, k;

	tablen = 0;
	max_len = 0;

	if( (in_fp = (FILE*) fopen(in_file, "r")) == NULL)  return -1;

	for (i = 0; i < MAXIDX; i++) {
		tab_idx[i].edge = tab_idx[i].used = 0;
		tab_idx[i].pe_text[0] = i + 0x20;
		for (k = 1; k < MAX_CHAR_PE; k++)
			tab_idx[i].pe_text[k] = '\0';
	}

	if(k_tab == NULL) {
		printf("k_tab is NULL\n");
		k_tab = (key_table*) calloc(MAXTAB, sizeof(key_table));
	}

	if(code_data == NULL) {
		printf("code_data is NULL\n");
		code_data = (char *) calloc(MAXBUF, sizeof(char));
	}

	p_code = code_data + OFFSET_START;

	if(read_file(in_fp) == -1) return -1;

	qsort(k_tab, tablen - 1, sizeof(key_table), tabcomp);

	if(c_tab == NULL) {
		printf("c_tab is NULL\n");
		c_tab = (code_table *) calloc(tablen, sizeof(code_table));
	}
	generate_code_table(tab_idx, c_tab, k_tab, &tablen, code_data, &p_code);
	for (i = 0; i < tablen; i++)
		record_char_use(tab_idx, (k_tab + i)->key);

	for (i = 1; i < MAXIDX; i++) {
		if (tab_idx[i].edge < tab_idx[i-1].edge)
			tab_idx[i].edge = tab_idx[i-1].edge;
	}

	write_code_table(im, tab_idx, c_tab, tablen, code_data, p_code - code_data);

	free(k_tab); k_tab = NULL;
	free(c_tab); c_tab = NULL;
	free(code_data); code_data = NULL;
}

read_file(fp)
FILE	*fp;
{
	read_text_ct(fp);
	fclose(fp);
	return 0;
}

is_bin_code_table(fd)
int	fd;
{
	char	header[32];

	read(fd, header, strlen(CODE_TABLE_HEAD));

	if (strcmp(header, CODE_TABLE_HEAD) == 0)
		return 1;
	lseek(fd, 0, 0);
	return 0;
}

read_bin_ct(fd)
int	fd;
{
	return -1;
}

read_text_ct(fp)
FILE    *fp;
{
	char	c, str[MAXLEN];
	unsigned char check;
	short	reading = OTHER;
	int	lineno = 0;
	int	i, k;
	char    arg[20], value[20];

	while (!feof(fp)) {
		fgets(str, MAXLEN, fp);
		if (feof(fp) || (str == NULL) || (strlen(str) < 1)) break;
		lineno++;
		if (str[0] == '#') {
			continue;
		}
		if (strncmp(str, CTINFO_ID, 16) == 0) {
			reading = CTINFO;
			strcpy(name, "Âë±íÊäÈë·¨");
			strcpy(locale, "zh_CN");
			wildchar = 'z';
			continue;
		}
		if (strncmp(str, KEYTABLE_ID, 18) == 0) {
			reading = KEYTABLE;
			continue;
		}
		if (strncmp(str, CODETABLE_ID, 11) == 0) {
			reading = CODETABLE;
			continue;
		}
		switch (reading) {
		case CTINFO:
			value[0] = '\0';
			sscanf(str,"%s%s", arg, value);
			if(!strcmp(arg, "name")) {
				if(strlen(value) > 0) strcpy(name, value);
				printf("name is %s\n", name);
			}
			else if(!strcmp(arg, "locale"))  {
				if(strlen(value) > 0) strcpy(locale, value);
				printf("locale is %s\n", locale);
			}
			else if(!strcmp(arg, "wildchar")) {
				if(strlen(value) > 0) wildchar = value[0];
				printf("wildchar is %c\n", wildchar);
			}
			break;

		case KEYTABLE:
			if (strlen(str) != 1) {
				fprintf(stderr, "Error: line %d\n", lineno);
				exit(1);
			}
			i = idx(str[0]);
			k = 0;
			while ((c = getc(fp)) != EOF && c != '\n') {
				if (isspace(c))
					continue;
				if (k >= MAX_CHAR_PE) {
					fprintf(stderr, 
					    "line %d: mapping string too long\n", 
					    lineno);
					break;
				}
				tab_idx[i].pe_text[k++] = c;
			}
			break;
		case CODETABLE:
			if( tablen >= MAXTAB ) break;
			sscanf(str,"%s%s", p_code, (k_tab + tablen)->key);
			check = p_code[0];
			if( (check < 0x80) || (strlen((k_tab + tablen)->key) < 1) ) {
				fprintf(stderr, "Codetable error, line %d , ignored.\n", lineno);
				break;
			}
			(k_tab + tablen)->code = p_code;
			p_code += strlen(p_code) + 1;
			if (strlen((k_tab + tablen)->key) > max_len)
				max_len = strlen((k_tab + tablen)->key);
			tablen++;
			break;
		default:
			fprintf(stderr, "File format error, line %d .\n", lineno);
			break;
		}
	}
}

tabcomp(ti1, ti2)
key_table *ti1, *ti2;
{
	int	r;

	if (r = strcmp(ti1->key, ti2->key))
		return r;
	return strcmp(ti1->code, ti2->code);
}


generate_code_table(tab_idx, c_tab, k_tab, tablen, code_data, p_code)
table_index	*tab_idx;
code_table	*c_tab;
key_table	*k_tab;
int		*tablen;
char		*code_data;
char		**p_code;
{
	int	i, size;
	short	*l, search_for();
	char	*p, *str;
	char	fc;		/* first char */

	size = *tablen;

	/* Make code table */
	fc = k_tab->key[0];
	tab_idx[idx(fc)].edge = 0;
	tab_idx[idx(fc)].used = 0;
	for (i = 0; i < size; i++) {
		if (fc != (k_tab + i)->key[0]) {
			tab_idx[idx(fc)].edge = i;
			fc = (k_tab + i)->key[0];
		}
		c_tab[i].key = encoding((k_tab + i)->key, code_data, p_code);
		c_tab[i].code = (k_tab + i)->code - code_data;
	}
	tab_idx[idx(fc)].edge = i;
}


short
search_for(code, code_data, c_tab, tablen)
char		*code, *code_data;
code_table	*c_tab;
int		*tablen;
{
	short	i;

	for (i = 0; i < *tablen; i++) {
		if (strcmp((char *) (c_tab[i].code + code_data), code) == 0) {
			return i;
		}
	}
	c_tab[i].code = c_tab[i-1].code + 
	    strlen((char *) (c_tab[i - 1].code + code_data)) + 1;
	strcpy((char *)(c_tab[i].code + code_data), code);
	*tablen += strlen(code) + 1;
	return i;
}


int write_code_table(im, tab_idx, c_tab, tablen, code_data, data_len)
engine_info	*im;
table_index	*tab_idx;
code_table	*c_tab;
int		tablen;
char		*code_data;
int	 	data_len;
{
	strcpy(im->name, name);
	strcpy(im->locale, locale);
	im->wild_char = wildchar;
	memcpy(im->tab_idx, tab_idx, sizeof(table_index) * MAXIDX);
	im->c_tab = (code_table *) malloc(sizeof(code_table) * tablen);
	memcpy(im->c_tab, c_tab, sizeof(code_table) * tablen);
	im->data = (char *) malloc(data_len);
	memcpy(im->data, code_data, data_len);
}


encoding(str, code_data, p_code)
char	str[];
char	*code_data;
char	**p_code;
{
	int	code = 0;
	int	n;

	if (strlen(str) <= 5) {
		for (n = 1; str[n] != '\0'; n++) {
			code += str[n] << (7 * (4 - n));
		}
	} else {
		strcpy(*p_code, (char *)&str[1]);
		code = KEYSTR_MASK + *p_code - code_data;
		*p_code += strlen(str);
	}
	return code;
}


record_char_use(tab_idx, str)
table_index	*tab_idx;
char		*str;
{
	while (*str != '\0') {
		tab_idx[idx(*str)].used = 1;
		str++;
	}
}

