/*
 * Author: piaip, 2002
 * All Rights Reserved
 *
 * $Id: myconv.c,v 1.2 2002/09/24 13:50:45 b7506051 Exp $
 * $Log: myconv.c,v $
 * Revision 1.2  2002/09/24 13:50:45  b7506051
 * Table-accerlated
 *
 * Revision 1.1  2002/09/24 13:50:00  b7506051
 * Initial revision
 *
 */

#include <stdio.h>
#include <stdlib.h>
#include <assert.h>

#define ISDBCS(x) (x >= 0x80)
#define CIN_FN "phone.cin.v2"
#define KEY_FN "phone.key"

unsigned char newtbl[65535];

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

FILE *fcin, *fkey;

char *lookup_bpmf(int c1, int c2) {
    static unsigned char retbuf[3];
    int index = c1 * 256 + c2;

    retbuf[0] = c1;
    retbuf[1] = c2;
    retbuf[2] = 0;

    assert(!(index < 0 || index >= sizeof(newtbl)));
    if(newtbl[index] != 0) {
	if(newtbl[index] >= 97) {
	    retbuf[0] = tbl_97[ (newtbl[index] - 97) * 2];
	    retbuf[1] = tbl_97[ (newtbl[index] - 97) * 2 + 1];
	} else if (newtbl[index] >= 44) {
	    retbuf[0] = tbl_44[ (newtbl[index] - 44) * 2];
	    retbuf[1] = tbl_44[ (newtbl[index] - 44) * 2 + 1];
	} else assert(0);
    }
    return retbuf;
}

int main(int argc, char *argv[]) {
    int c = 0;
    int c2 = 0;
    char *msg = NULL;

    if(argc > 1) {
	if(!freopen(argv[1], "r", stdin)) {
	    fprintf(stderr, "Cannot open '%s'\n\r", argv[1]);
	    return 1;
	}
    }

    fcin = fopen(CIN_FN, "rt");
    //fkey = fopen(KEY_FN, "rt");

    if(fcin == NULL) {
	fprintf(stderr, "Cannot open " CIN_FN "\n\r");
	return 1;
    }
    if(fread(newtbl, sizeof(newtbl), 1, fcin) != 1) {
	fprintf(stderr, "Cannot read correct " CIN_FN "\n\r");
	return 1;
    };
    fclose(fcin);
    /* for using with telnet/... etc */
    setbuf(stdin, NULL);
    setbuf(stdout, NULL);

    while((c = fgetc(stdin)) != EOF) {
	if(ISDBCS(c)) {
	    c2 = fgetc(stdin);
	    msg = lookup_bpmf(c, c2);
	    printf(msg);
	} else {
	    putchar(c);
	}
    }

    return 0;
}
