/*
 * Copyright (C) 1995	Edward Der-Hua Liu, Hsin-Chu, Taiwan
 * Read: pho1st
 * Write: pho.sel1st
 */

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

typedef struct {
    u_char          ch[2];
    u_short         ph;
}               ITEM;

u_short         hash[256], defh[256];
ITEM            it[19000];
int             num;

static char    *pk[] = {
    "  £t£u£v£w£x£y£z£{£|£}£~£¡£¢£££¤£¥£¦£§£¨£©£ª",
    "  £¸£¹£º",
    "  £«£¬£­£®£¯£°£±£²£³£´£µ£¶£·",
    "  £»£½£¾£¿"
};

static int      shiftb[] = {9, 7, 3, 0};

int lookup(u_char * s)
{
    int             i;
    char            tt[3], *pp;


    if (*s < 128)
	return *s - '0';
    tt[0] = s[0];
    tt[1] = s[1];
    tt[2] = 0;
    for (i = 0; i < 3; i++)
	if (pp = strstr(pk[i], tt))
	    break;
    if (i == 3)
	return 0;
    return (((pp - pk[i]) >> 1) << shiftb[i]);
}

void 
prph(u_short kk)
{
    u_int           k1, k2, k3, k4;
    k4 = (kk & 7) << 1;
    kk >>= 3;
    k3 = (kk & 15) << 1;
    kk >>= 4;
    k2 = (kk & 3) << 1;
    kk >>= 2;
    k1 = (kk & 31) << 1;
    printf("%c%c%c%c%c%c%c%c",
	   pk[0][k1], pk[0][k1 + 1],
	   pk[1][k2], pk[1][k2 + 1],
	   pk[2][k3], pk[2][k3 + 1],
	   pk[3][k4], pk[3][k4 + 1]);
}

int qcmp(ITEM * a, ITEM * b)
{
    return ((int)a->ph - (int)b->ph);
}

int main()
{
    FILE           *fp;
    char            s[128];
    int             i, len, cou;
    u_short         kk;
    u_char          tt[3];

    if ((fp = fopen("pho1st", "r")) == NULL) {
	puts("t.lut err");
	exit(-1);
    }
    cou = 0;
    while (!feof(fp)) {
	fgets(s, sizeof(s), fp);
	len = strlen(s);
	if (s[len - 1] == '\n')
	    s[--len] = 0;
	if (!len)
	    break;
	memcpy(tt, s, 2);
	kk = 0;
	for (i = 3; i < len; i += 2) {
	    kk |= lookup(&s[i]);
	}
	it[cou].ph = kk;
#if	0
	prph(kk);
	puts("");
#endif
	memcpy(it[cou++].ch, tt, 2);
    }
    fclose(fp);

    qsort(it, cou, sizeof(ITEM), (void *)qcmp);

    bzero(defh, sizeof(defh));
    for (i = 0; i < cou; i++) {
	int             idx = it[i].ph >> 6;
	if (!defh[idx]) {
	    defh[idx] = 1;
	    hash[idx] = i;
	}
    }
    hash[255] = cou;
    for (i = 254; i >= 0; i--) {
	if (!defh[i]) {
	    hash[i] = hash[i + 1];
	}
    }

    if ((fp = fopen("pho.sel1st", "w")) == NULL) {
	puts("pho.sel1st");
	exit(1);
    }
    fwrite(&cou, 4, 1, fp);
    fwrite(hash, 2, 256, fp);
    fwrite(it, sizeof(ITEM), cou, fp);
    fclose(fp);
    exit(0);
}
