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

typedef unsigned char	uchr;

main(ac, av)
int	ac;
char	**av;
{
    int		c, c1, c2;
    int		sjis, kmode, knj1;
    FILE	*infp, *outfp;

    if (ac != 3) {
	printf("pp infile outfile\n");
	exit(1);
    }
    if ((infp = fopen(av[1], "r")) == NULL) {
	printf("Can't open infile %s\n", av[1]);
	exit(1);
    }
    if ((outfp = fopen(av[2], "w")) == NULL) {
	printf("Can't open outfile %s\n", av[2]);
	exit(1);
    }
    sjis = 0;
    while ((c = getc(infp)) != EOF) {
	if (c >= 0x81 && c <= 0x9f)
	    sjis = 1;
    }
    clearerr(infp);
    rewind(infp);
    kmode = 0;
    knj1 = 0;
    while ((c = getc(infp)) != EOF) {
	if (knj1 != 0) {
	    if (!sjis) {
		knj1 &= 0x7f;
		c &= 0x7f;
		if ((knj1 & 0x01) == 0) {
		    c += 0x7e;
		} else {
		    c += 0x1f;
		    if (c > 0x7e)
			c++;
		}
		knj1 = (knj1 + 0xe1) >> 1;
		if (knj1 > 0x9f)
		    knj1 += 0x40;
	    }
	    fprintf(outfp, "\\%03o\\%03o", knj1, c);
	    knj1 = 0;
	    continue;
	}
	if (c == '\033') {
	    c1 = getc(infp);
	    c2 = getc(infp);
	    if (c1 == '$' && (c2 == '@' || c2 == 'B'))
		kmode = 1;
	    else if (c1 == '(' && (c2 == 'J' || c2 == 'B'))
		kmode = 0;
	    continue;
	}
	if ((c & 0x80) || kmode == 1) {
	    knj1 = c;
	    continue;
	}
	if (c == '\r')
	    continue;
	putc(c, outfp);
    }
    fclose(infp);
    fclose(outfp);
    exit(0);
}


syntax highlighted by Code2HTML, v. 0.9.1