/*
 * Copyright (C) 1994	Edward Der-Hua Liu, Hsin-Chu, Taiwan
 * Read: phonetic.tab
 * Write: pho.tab
pho.tab struct
  PH(2)
  idxnum(2)
  tab(2)*idxnum(2)
  ch(1)*wc
    idxnum is index number [2638]
    wc is chardef number [28286]
 */

#include <stdio.h>
#include <sys/types.h>

u_char          dat[30000];
u_char          ch[32000];


FILE           *fp;
u_short         ofs;
u_char         *pp;

int main()
{
    u_short         i, j, k, l;
    u_short         wc = 0;
    u_short         tab[2800];
    u_short         idxnum = 0;

    if ((fp = fopen("phonetic.tab", "rb")) == NULL) {
	printf("err open phonetic.tab\n");
	exit(-1);
    }
    fread(dat, 1, sizeof(dat), fp);

    for (i = 0; i <= 21; i++)
	for (j = 0; j <= 3; j++)
	    for (k = 0; k <= 13; k++)
		for (l = 0; l <= 4; l++) {
		    u_short         key1 = (i * 5 + l) << 1;
		    u_short         key2 = (j * 16 + k);
		    u_short         ofs, endofs;

		    pp = &dat[key1];
		    ofs = (*pp) | ((u_short) * (pp + 1) << 8);
		    endofs = *(pp + 2) | ((u_short) * (pp + 3) << 8);

		    while (dat[ofs] != key2 && ofs < endofs) {
			ofs = ofs + 1;
			while (dat[ofs] >= 128)
			    ofs += 2;
		    }

		    if (dat[ofs] != key2 || ofs >= endofs)
			continue;

		    tab[idxnum++] = i << 9 | j << 7 | k << 3 | l;
		    if (tab[idxnum - 1] > 0x8000)
			puts("err");
#ifdef	DEBUG
		    printf("%4x %2x|", tab[idxnum - 1], tab[idxnum - 1] >> 9);
#endif
		    tab[idxnum++] = wc;

		    ofs++;
		    while (dat[ofs] >= 128 && ofs < endofs) {
			ch[wc++] = dat[ofs++];
			ch[wc++] = dat[ofs++];
		    }
		}

    fclose(fp);
    if ((fp = fopen("pho.tab", "w")) == NULL) {
	printf("err open pho.tab");
	exit(-1);
    }
    fwrite("PH", 1, 2, fp);
    fwrite(&idxnum, 2, 1, fp);

#ifdef	DEBUG
    printf("idxnum %x\n", idxnum);
#endif

    for (i = 0; i < idxnum >> 1; i += 2)
	if (tab[i] > 0x8000)
	    printf("err %x\n", tab[i]);
    fwrite(tab, 2, idxnum, fp);
    fwrite(ch, 1, wc, fp);
    fclose(fp);
    exit(0);
}
