/*
 * UNICON - The Console Chinese & I18N
 * Copyright (c) 1999-2002
 *
 * This file is part of UNICON, a console Chinese & I18N
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * 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.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 *
 * See the file COPYING directory of this archive
 * Author: see CREDITS
 */

#include <stdio.h>
#include <ctype.h>
#include <stdarg.h> 
#include <sys/types.h>
#include <string.h>
#include <unistd.h>
#include <xl_hzinput.h>
#include <xl_sysphrase.h>
#include <xl_phrase.h>
#include <PhraseLevel.h>

// maximum char/phrase can be defined
#define ERROR_FOPEN				1
#define	ERROR_READFILE			2
#define ERROR_WRONGFORMAT		3
#define ITEM_MAXSIZE            65535
#define LINE_MAX_LEN			128
#define COMMENT_CHAR			'#'
FILE	*fr, *fw;
int		lineno;
ITEM	ItemOut[ITEM_MAXSIZE];

TL_SysPhrase_T	*pDefaultSysphrase = NULL;
static char		*TL_SYSPHRASE_FILE = "tl_sysphrase.bin";

#if 0
static void print_error (char *fmt,...)
{
    va_list args;

    va_start (args, fmt);
    vfprintf (stderr, fmt, args);
    va_end (args);
    fprintf (stderr,"\n");
    exit (-1);
}
#endif

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

    return s;
}

static char *to_space (char *s)
{
    while (*s && *s!=' ' && *s!='\t')
		s++;

    return s;
}

static void del_nl_space (char *s)
{
    char *t;
    int len;

    if (!*s) 
        return;

	len = strlen (s);
    t = s + len - 1;

    while ((*t=='\n' || *t==' ' || *t=='\t') && ((t+1) >= s)) 
        t--;

    *(t+1)=0;
}

static int get_line (u_char *line)
{
	int endfile = 0;
	do
	{
		if (fgets (line, LINE_MAX_LEN, fr) == NULL)
			endfile = 1;
		else
			lineno ++;
	}
	while (line[0] == COMMENT_CHAR); // Skip Comments

	return endfile;
}

static void cmd_arg (u_char *line, u_char **cmd, u_char **arg)
{
    char *t;

    if (!*line)
	{
		*cmd = *arg = line;
		return;
	}

    line = skip_space (line);
    t=to_space (line);
    *cmd = line;
    if (! (*t))
	{
    	*arg = t;
    	return;
    }

	// terminate the string (cmd)
    *t=0;
    t++;
    t = skip_space (t);
    del_nl_space (t);
    *arg = t;
}

// Get the Phrase Frequence
count_t  GetPhraseLevel (unsigned long count)
{
    int i;
    for (i = 1; i < 256; i++)
    {
        if (count >= PhraseLevel[i-1] && count < PhraseLevel[i])
            return i - 1;
    }
    return 255; 
}

void  ProcessingSystemPhrase (char *FileName)
{
	FILE *fp;
	char line[LINE_MAX_LEN];
	u_char *cmd, *arg;
	u_long count;

	if ((fp = fopen (FileName, "rt")) == NULL)
	{
		perror (FileName);
		exit (ERROR_FOPEN);
	}

	lineno = 1;
	fr = fp;
	while (get_line (line) != 1)
	{
		cmd_arg (line, &cmd, &arg);

		if (!cmd[0] || !arg[0])
		{
			fprintf (stderr, "Error in reading %s\n", FileName);
			fclose (fp);
			exit (ERROR_READFILE);
		}

		if (isdigit (cmd[0]))
		{
			count = atol (cmd);
			TL_AddPhrase (pDefaultSysphrase, arg, GetPhraseLevel (count));
		}
		else
		{
			fprintf (stderr, "Wrong format in file: %s\n", FileName);
			fclose (fp);
			exit (ERROR_WRONGFORMAT);
		}
	}
	printf ("Processing %s, No of Line is %d\n", FileName, lineno);
	fclose (fp); 
}

int main (int argc, char **argv)
{
	char *WordPhraseFileName = NULL;
	char *CharPhraseFileName = NULL;
	char *DumpPhraseFileName = NULL;
	int opt;
	extern char *optarg;
	extern int optind;

	if (argc<=1) 
	{
		printf ("%s [-o <System Phrase File>] \n \
					\t -c <Char Phrase Filename> \n \
					\t -w <Word Phrase Filename> \n \
					\t -d <dump SysPhrase File> \n", 
					argv[0]);
		exit (1);
	}

#define ACCEPTOPTS      "o:c:d:w:"
	while ((opt = getopt(argc, argv, ACCEPTOPTS)) != -1) 
	{
#undef ACCEPTOPTS
		switch (opt) 
		{
			case 'o':
				TL_SYSPHRASE_FILE = optarg;
				break;
			case 'c':
				CharPhraseFileName = optarg;
				break; 
			case 'w':
				WordPhraseFileName = optarg;
				break;
			case 'd':
				DumpPhraseFileName = optarg;
				break;
			default:
				printf ("Error in Parameter \n");
				exit (0);
		} 

	}

	pDefaultSysphrase = LoadSystemPhrase (TL_SYSPHRASE_FILE, 0);
	if (pDefaultSysphrase == NULL)
	{
		// Create a new structure.
		pDefaultSysphrase = malloc (sizeof (TL_SysPhrase_T));
		if (pDefaultSysphrase == NULL)
			perror ("main >> malloc ()");

		pDefaultSysphrase->TotalPhrase =0;
		pDefaultSysphrase->pPhrase = NULL;
	}

	if (WordPhraseFileName != NULL)
		ProcessingSystemPhrase (WordPhraseFileName);

	if (CharPhraseFileName != NULL)
		ProcessingSystemPhrase (CharPhraseFileName);

	if (DumpPhraseFileName != NULL)
		TL_DumpAllPhrase (pDefaultSysphrase, DumpPhraseFileName);

	TL_SaveAllPhrase (pDefaultSysphrase, TL_SYSPHRASE_FILE);
	return 0;
}
