/*
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.

*/
#define _POSIX_PTHREAD_SEMANTICS

#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <fcntl.h>

#ifdef WIN32
#include <windows.h>
#include <stdlib.h>
#include <string.h>
#include <direct.h>
#else
#include <dirent.h>
#include <sys/types.h>
#include <unistd.h>
#endif

#include "CodeTable.h"
#include "UDEngine.h"

extern engine_info **im;

#ifndef WIN32
char** get_list_of_codetable(char * pathname) {
	DIR *dir;
	struct dirent *result;
	struct dirent *entry;
	int ret_val;
	char *ext;
	int i;
	char **ct_list;

	ct_list = (char **) malloc(sizeof(char *) * 100);
	dir = opendir(pathname);
	if (!dir) {
		printf("can not open dir %s\n", pathname);
		free(ct_list);
		return NULL;
	}
	entry = (struct dirent *) malloc(sizeof(struct dirent) + FILENAME_MAX);
	i = 0;
	while ((ret_val = readdir_r(dir, entry, &result)) == 0) {
		if (!result)
			break;
		ext = strrchr(result->d_name, (int) '.');
		if (ext) {
			if ( (i < 99) && (!strcmp(".mb", ext)) )   {
				printf("file : %s\n", result->d_name);
				ct_list[i] = (char *) malloc(strlen(pathname) + strlen(result->d_name) + 1);
				strcpy(ct_list[i], pathname);
				strcat(ct_list[i], "/");
				strcat(ct_list[i], result->d_name);
				i ++;
			}
		}
	}
	ct_list[i] = NULL;
	if( i == 0 ) {
		free(ct_list);
		ct_list = NULL;
	}
	free(entry);
	closedir(dir);
	return (char **)ct_list;
}

#else
char** get_list_of_codetable(char * pathname) {
	char *ext;
	char *compl_pathname;
	int i = 0;
	char *name;
	BOOL hasMore;
	WIN32_FIND_DATA finddata;
	char *filter = "\\*.mb";
	char **ct_list;

	ct_list = (char **) malloc(sizeof(char *) * 100);
	compl_pathname = (char*) malloc([strlen(pathname) + strlen(filter) + 1]);
	sprintf(compl_pathname, "%s%s", pathname, filter);

	/* Check if the path is valid */
	    DWORD dattrib = GetFileAttributes(pathname);
	if (dattrib == -1)
		return NULL;
	if (!(dattrib & FILE_ATTRIBUTE_DIRECTORY))
		return NULL;

	HANDLE dirhand = FindFirstFile(compl_pathname, &finddata);
	if (dirhand == (HANDLE) - 1)
		return NULL;
	do {
		name = (LPSTR) & finddata.cFileName;
		ext = strrchr(name, (int) '.');
		if (ext) {
			if ( (i < 99) && (!strcmp(".mb", ext)) )   {
				printf("file : %s\n", name);
				ct_list[i] = (char *) malloc(strlen(pathname) + strlen(name) + 1);
				strcpy(ct_list[i], pathname);
				strcat(ct_list[i], "/");
				strcat(ct_list[i], name);
				i ++;
			}
		}
		hasMore = FindNextFile(dirhand, &finddata);
	} while (hasMore);

	ct_list[i] = NULL;
	if( i == 0 ) {
		free(ct_list);
		ct_list = NULL;
	}
	return (char **)ct_list;
}
#endif

int is_preedit_char(int imid, char c) {
	if(im[imid]->tab_idx[idx(c)].used) return 1;
	else return 0;
}

int read_code_table(int imid)
{
	int     fd, i;
	int     tablen, data_len, max_len;
	char    header[80];
	char *ct_file_name;
	char    *buf, *tmp;

	ct_file_name = (char*) im[imid]->ct_file;

	if ((fd = open(ct_file_name, O_RDONLY)) == -1) {
		return -1;
	}

	read(fd, header, strlen(CODE_TABLE_HEAD));
	if (strncmp(header, CODE_TABLE_HEAD, strlen(CODE_TABLE_HEAD)) != 0) {
		close(fd);
		if( make_code_table(im[imid], ct_file_name) == -1) return -1;
		return 0;
	}
	read(fd, &tablen, sizeof(int));
	read(fd, &data_len, sizeof(int));
	read(fd, &max_len, sizeof(int));
	read(fd, im[imid]->tab_idx, sizeof(table_index) * MAXIDX);
	im[imid]->c_tab = (code_table *) malloc(sizeof(code_table) * tablen);
	im[imid]->data = (char *) malloc(data_len);
	read(fd, im[imid]->c_tab, sizeof(code_table) * tablen);
	read(fd, im[imid]->data, data_len);
	close(fd);
	return 0;
}

find_candidate(imid, str, low, high)
int 		imid;
unsigned char   *str;
int             *low;
int             *high;
{
	int     d, i, h, l;

	for (l = im[imid]->tab_idx[idx(str[0]) - 1].edge,
	    h = im[imid]->tab_idx[idx(str[0])].edge - 1; l < h; ) {
		i = (l + h) / 2;
		if ((d = match(imid, (char *)&str[1], i)) == 0)
			break;
		if (d > 0)
			l = i + 1;
		else h = i - 1;
	}

	if (l < h) {
		for (l = i; l > im[imid]->tab_idx[idx(str[0]) - 1].edge; l--) {
			if (match(imid, (char *)&str[1], l-1) != 0)
				break;
		}
		for (h = i; h < im[imid]->tab_idx[idx(str[0])].edge - 1; h++) {
			if (match(imid, (char *)&str[1], h+1) != 0)
				break;
		}
		*low = l;
		*high = h;
		return;
	}

	if (l == h && match(imid, (char *)&str[1], l) == 0) {
		*low = *high = l;
		return;
	}

	*low = 1;
	*high = 0;
}

match(imid, keystr, idx)
int     imid;
char    *keystr;
int     idx;
{
	code_table      *ct_item = (code_table *) &(im[imid]->c_tab[idx]);
	char            *data = im[imid]->data;
	int     i;
	int     len = strlen(keystr);
	char    *tab_str, buf[8];

	if (ct_item->key & KEYSTR_MASK) {
		tab_str = (char *)(ct_item->key - KEYSTR_MASK + data);
	} else {
		for (i = 0; i < 4; i++) {
			buf[i] = (ct_item->key >> (7 * (3 - i))) & 0x7f;
		}
		buf[4] = '\0';
		tab_str = buf;
	}

	return strncmp(keystr, tab_str,len);
}

make_selections(imid, selections, low, high, dir, len, encode, max_number)
int 	imid;
char    **selections;
int     *low, high;
int     dir;
int     len;
char*   encode;
int	max_number;
{
	int     i, j, k;
	char    *p, buf[64], t[64], t1[64];
	int     number;
	int	direction;
	int	flag;

#ifdef DEBUG
printf("high = %d, low = %d, dir = %d, encode = %s\n", high, *low, dir, encode);
#endif

	if(dir == 1) {
		number = high - *low + 1;
		direction = 1;
	}
	else {
		number = *low - high + 1;
		direction = -1;
	}
	for (i = 0, j = 0; (i * direction) < number; i += direction) {
		flag = 0;
		p = (char *)(im[imid]->data +
		    im[imid]->c_tab[*low + i].code);
		if (len == 0 || keylen(im[imid]->c_tab[*low + i].key, *encode, p, buf) >= len) {
			if (len != 0) p = buf;
			sscanf(p, "%s%s", t, t1);
			if((len != 0) && (len < strlen(encode))) {
				for(k = len; k < strlen(encode); k ++) {
					if(!t1[k]) { flag = 1; break; }
					else if((encode[k] != encode[len - 1]) && (t1[k] != encode[k])) { 
						flag = 1; break; 
					}
				}
			}
			if(!flag) {
				strcpy(selections[j], p);
#ifdef DEBUG
printf("%s \n", selections[j]);
#endif
				selections[j][20] = '\0';
				j++;
			}
		}
		if(j == max_number) {
			i += direction;
			break;
		}
	}
#ifdef DEBUG
printf("\n j = %d\n", j);
#endif
	*low += i;
#ifdef DEBUG
printf("\n low = %d\n", *low);
#endif
	if (j == 0) return 0;
	if(direction == -1) {
		for(i = 0; i < j / 2; i ++) {
			strcpy(t, selections[i]);
			strcpy(selections[i], selections[j - i - 1]);
			strcpy(selections[j - i - 1], t);
		}
	}
	return j;
}

keylen(k, fc, cstr, buf)
int     k;
char    fc, *cstr, *buf;
{
	int     i;
	char    c, *s;

	sprintf(buf, "%s %c", cstr, fc);
	s = &buf[strlen(buf)];
	for (i = 1; i < 5; i++) {
		if ((c = ((k >> (4 - i) * 7) & 0x7f)) == 0)
			break;
		*s++ = c;
	}
	*s = '\0';
	return i;
}

