#include "defs.h"

/*
 * A filter converting a 7-bit ISO-2022 encoding using CNS (on standard
 * input) to Big-5 (on standard output).
 */

#define	ESC	'\033'

static	MODE	get_shift(void);

int main(int argc, char *argv[])
{
	unsigned char	b5[2], cns[3];
reg	int	c;
reg	MODE	mode, new_mode;

	mode = ASCII;
	while ((c = getchar()) != EOF)
		if (c == ESC)
			if ((new_mode = get_shift()) == ERROR)
				fprintf(stderr,
					"%s: invalid escape sequence\n",
					argv[0]);
			else {
				mode = new_mode;
				cns[0] = mode == CNS1 ? 0x21 : 0x22;
			}
		else if (mode == ASCII)
			putchar(c);
		else {
			cns[1] = c;
			if ((c = getchar()) == EOF) {
				fprintf(stderr, "%s: incomplete hanzi\n",
					argv[0]);
				break;
			}
			cns[2] = c;
			CNStoBig5(b5, cns);
			putchar(b5[0]);
			putchar(b5[1]);
		}
	return 0;
}

static MODE get_shift(void)
{
reg	int	c;

	if ((c = getchar()) == '(')
		return (c = getchar()) == 'B' ? ASCII : ERROR;
	if (c != '$' || (c = getchar()) != '(')
		return ERROR;
	return (c = getchar()) == 'G' ? CNS1 : c == 'H' ? CNS2 : ERROR;
}
