/*
Copyright 1990-2003 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 <ctype.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

enum {
	OK = 0,
	ERROR = -1,
	ERROR_ZHICODE = -2,
	ERROR_ZHUYINCODE = -3,
};

/* define struct for file with text format */
typedef struct {
	unsigned char *Yin;
	unsigned char *ZhiList;
} TTextItemStruct, *PTextItemStruct;

typedef struct {
	long num_items;
	PTextItemStruct *items;
} TTextItemListStruct;

#define LEN_BUFFER_ALLOC  5000

char *skip_space(char *s)
{
	while (*s && (*s==' ' || *s=='\t')) s++;
	return s;
}

char *to_space(char *s)
{
	while (*s && !(isspace(*s) || *s == '\n')) s++;
	return s;
}

char *trim_string(char *s)
{
	char *head_ptr, *tail_ptr;

	if (!s || !*s) return(s);

	head_ptr = s;

	/* trim left space */
	while(*head_ptr && (*head_ptr == ' ' || *head_ptr == '\t' || *head_ptr == '\n'))
		head_ptr ++;

	if (!*head_ptr) return(head_ptr);

	/* trim right space */
	tail_ptr = head_ptr + strlen(head_ptr) - 1;
	
	while(*tail_ptr && (*tail_ptr == ' ' || *tail_ptr == '\t' || *tail_ptr == '\n')) {
		*tail_ptr = '\0';
		tail_ptr --;
	}

	return(head_ptr);
}

/*
parse the line into gbk_code, Zhi and frequence:

return OK if success;
return ERROR_ZHICODE  if gbk_code error;
return ERROR_ZHUYINCODE if Zhi error;
*/

int parse_line_for_zhuyin(char *line_buf, TTextItemStruct *item)
{
	char key_sequence[5];
	char *ptr, *yin_ptr, *zhi_ptr;
	int  yin_len;

	ptr = trim_string(line_buf);

	if (*ptr == '\n' || *ptr == '#') 
		return(ERROR);

	yin_ptr = ptr;
	ptr = to_space(ptr);
	*ptr = '\0';
	
	ZhuyinSymbolSequenceToStandardKeySequence(yin_ptr, key_sequence, &yin_len);

	if (yin_len == 0) return(ERROR_ZHUYINCODE);

	if (item->Yin != NULL) free((char *)item->Yin);
	item->Yin = (unsigned char *)strdup(key_sequence);

	zhi_ptr = skip_space(ptr+1);
	ptr = to_space(ptr);
	*ptr = '\0';

	if (*zhi_ptr == 0) return(ERROR_ZHICODE);

	if (item->ZhiList != NULL) free((char *)item->ZhiList);
	item->ZhiList = (unsigned char *)strdup(zhi_ptr);

	return(OK);
}

int TextItemList_Alloc(TTextItemListStruct *ItemList, int num_alloced)
{
	int i;

	ItemList->num_items = 0;
	ItemList->items = malloc(num_alloced * sizeof(PTextItemStruct*));

	if (ItemList->items == NULL) {
		fprintf(stderr, "Error: TextItemList malloc\n");
		return(ERROR);
	}

	for (i=0; i<num_alloced; i++)
		ItemList->items[i] = NULL;

	ItemList->num_items = num_alloced;
	
	return(OK);
}

int TextItemList_ReAlloc(TTextItemListStruct *ItemList, int num_alloced)
{
	int i;

	ItemList->items = realloc((void *)ItemList->items, num_alloced * sizeof(PTextItemStruct*));

	if (ItemList->items == NULL) {
		fprintf(stderr, "Error: TextItemList realloc\n");
		ItemList->num_items = 0;
		return(ERROR);
	}

	for (i=ItemList->num_items; i<num_alloced; i++)
		ItemList->items[i] = NULL;

	ItemList->num_items = num_alloced;
	
	return(OK);
}

int TextItemList_Init(TTextItemListStruct *ItemList)
{
	ItemList->num_items = 0;
	ItemList->items = NULL;
}

int TextItemList_Free(TTextItemListStruct *ItemList)
{
	int i, j;

	for (i=0; i<ItemList->num_items; i++) {
		if (ItemList->items[i]->Yin != NULL) 
			free((char *)ItemList->items[i]->Yin);

		if (ItemList->items[i]->ZhiList != NULL) 
			free((char *)ItemList->items[i]->ZhiList);

		if (ItemList->items[i] != NULL)
			free((char *)ItemList->items[i]);
	}

	if (ItemList->items != NULL)
		free((char *)ItemList->items);

	ItemList->num_items = 0;

	return(OK);
}

int TextItem_Compare_By_YinCode(const void *p1, const void *p2)
{
	TTextItemStruct *item1 = *((TTextItemStruct **)p1);
	TTextItemStruct *item2 = *((TTextItemStruct **)p2);
	int ret;

	ret = strcmp(item1->Yin, item2->Yin);

	return(ret);
}

int TextItemList_Sort(TTextItemListStruct *ItemList, int(*compare)(const void *, const void *))
{
	qsort((void *)ItemList->items, ItemList->num_items, sizeof(PTextItemStruct), compare);
}

int TextItemList_Print_For_Single(TTextItemListStruct *ItemList)
{
	int i, j;
	unsigned char *Yin;
	unsigned char *ZhiList;
	long frequence;

	for (i=0; i<ItemList->num_items; i++) {
		if (ItemList->items[i] == NULL) {
			continue;
		}

		Yin = ItemList->items[i]->Yin;
		if (!Yin || !*Yin) break;

		ZhiList = ItemList->items[i]->ZhiList;
		if (!ZhiList || !*ZhiList) break;

		printf("%s\t%s\n", (char *)Yin,  ZhiList);
	}
}

int Read_TextItemList_From_File(char *file_name, TTextItemListStruct *ItemList, int(*parse_line)(char *, TTextItemStruct *))
{
	FILE *ifile;
	char line_buf[256];

	int num_malloc_items = LEN_BUFFER_ALLOC;
	int num_items = 0;
	int line_no = 0;
	int ret;

	ifile = fopen(file_name, "r");
	if (ifile == NULL) {
		fprintf(stderr, "Error: open file %s\n", file_name);
		return(ERROR);
	}

	TextItemList_Alloc(ItemList, num_malloc_items);

	while(fgets(line_buf, 256, ifile) != NULL) {

		line_no++;

		/* realloc buffer for items */
		if (num_items >= num_malloc_items) {
			num_malloc_items += LEN_BUFFER_ALLOC;
			ret = TextItemList_ReAlloc(ItemList, num_malloc_items);
			if (ret == ERROR) 
				break;
		}
		
		if (ItemList->items[num_items] == NULL) {
			ItemList->items[num_items] = (TTextItemStruct *)calloc(1, sizeof(TTextItemStruct));
			if (ItemList->items[num_items] == NULL) {
				fprintf(stderr, "Error:  No Memory for TextItemList\n");
				break;
			}
		}

		ret = parse_line(line_buf, ItemList->items[num_items]);
		if (ret != 0) {
			if (ret == ERROR_ZHICODE) {
				fprintf(stderr, "Error: hz_code error in line %d\n", line_no);
			} else if (ret == ERROR_ZHUYINCODE) {
				fprintf(stderr, "Error: Zhi error in line %d\n", line_no);
			}
			continue;
		} 

		num_items++;
	}

	TextItemList_ReAlloc(ItemList, num_items);

	fclose(ifile);
	return(OK);
}

int main(int argc, char **argv)
{
	int ret = OK;
	char *zhuyin_file;

	TTextItemListStruct Zhuyin_ItemList;

	if (argc != 2) {
		printf("Usage:  %s zhuyin_file\n", argv[0]);
		exit(-1);
	}

	zhuyin_file = argv[1];

	ret = Read_TextItemList_From_File(zhuyin_file, 
					  &Zhuyin_ItemList, 
					  parse_line_for_zhuyin);
	if (ret == ERROR) {
		TextItemList_Free(&Zhuyin_ItemList);
		exit(-1);
	}

/*
	TextItemList_Sort(&Zhuyin_ItemList, TextItem_Compare_By_ZhuyinCode);
*/
	TextItemList_Print_For_Single(&Zhuyin_ItemList);
	TextItemList_Free(&Zhuyin_ItemList);

	return(OK);
}
