/*
 *
 * 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 <stdarg.h> 
#include <ctype.h>
#include <sys/types.h>
#include <string.h>
#include <unistd.h>
#include "xl_hzinput.h"

#define	ERROR_FOPEN				1
#define	ERROR_READFILE			2
#define	ERROR_WRONGFORMAT		3
#define	COMMENT_CHAR			'#'
#define	LINE_MAX_LEN			128
#define PHR_MARK_MAXSIZE		1000000ul
#define RESULT_MAXSIZE			256


FILE *fr, *fw;
int lineno;

// maximum char/phrase can be defined
u_char	PhraseMark [PHR_MARK_MAXSIZE];
u_long	Result [RESULT_MAXSIZE];


#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 

// Return pointer to the first non-whitespace char of the string 'S'
static char *skip_space (char *s)
{
	while (*s && (*s==' ' || *s=='\t'))
		s++;

	return s;
}

// Return pointer to the first whitspace char of the string 'S'
static char *to_space (char *s)
{
	while (*s && *s!=' ' && *s!='\t')
		s++;

	return s;
}

// Delete all traling white space and new line char of the string 'S'
static void del_nl_space (char *s)
{
	char *t;
	int len;

	if (!*s) 
		return;

	len = strlen (s);
	// 't' points to the last character
	t = s + len - 1;

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

	*(t+1) = 0;
}

// Read line from global variable : 'fr'
// Return 1 if end of file.
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;
}

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

    if ((fp = fopen (FileName, "r")) == 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);
		}
		else
		{
			fprintf (stderr, "Wrong format in file: %s\n", FileName);
			fclose (fp);
			exit (-1);
		}  

		if (count < PHR_MARK_MAXSIZE)
			PhraseMark[count] ++;
	}
	printf ("Processing %s, No of Line is %d\n", FileName, lineno);
	fclose (fp); 
}

void ProcessResult (void)
{
	long n = 0, m, i, t;
	int nstep = 0;

	memset (Result, 0, RESULT_MAXSIZE);

	for (i = 0; i < PHR_MARK_MAXSIZE; i++)
	{
		if (PhraseMark[i])
			n++;
	}

	printf ("Total = %ld\n", n);
	nstep = n / 256;

	for (t = 0, m = 0, i = 0; i < PHR_MARK_MAXSIZE; i++)
	{
		if (PhraseMark[i])
		{
			if (m % nstep == 0)
				 Result[t++] = i;
			m++;
		}
	} 
}

void WriteAllResult (char *FileName)
{
    FILE *fp;
    int i;

    fp = fopen (FileName, "w");

    fprintf (fp, "unsigned long int PhraseLevel[256] = { \n");
    for (i = 0; i  < RESULT_MAXSIZE; i++)
    {
        if (i % 4 == 0)
            fprintf (fp, "%s", (i)?"\n\t":"\t");

        fprintf (fp, "%ld%s", Result [i], (i != RESULT_MAXSIZE-1) ? ", ":"\n");
    }
    fprintf (fp, "};\n");

    fclose (fp);
}

int main (int argc, char **argv)
{
	int cnt;

	memset (PhraseMark, 0, PHR_MARK_MAXSIZE);

	for (cnt = 1; cnt < argc; cnt++)
		ProcessingSystemPhrase (argv[cnt]);

	ProcessResult ();
	WriteAllResult ("PhraseLevel.h");

	return 0;
}
