#!/usr/local/bin/perl
;#
;# pkf: Perl Kanji Filter
;#
;# Copyright (c) 1991,1992 Software Research Associates, Inc.
;#	by srekcah@sra.co.jp, Febuary 1992
;#
;#	Maintained by Kazumasa Utashiro <utashiro@sra.co.jp>
;#	Software Research Associates, Inc., Japan
;#
;; $rcsid = q$Id: pkf,v 1.8 1993/06/23 02:16:51 utashiro Exp $;
;; $pkf = ('pkf', split('/', $0));
;;
;; Usage:				($usage = <<";#-") =~ s/(^|\n);#/\1/g;
;#	$pkf [option] [-[icode]ocode[in,out]] files
;#
;#	icode/ocode is one of [jse] (j=JIS, s=SJIS, e=EUC)
;#	ocode `j' can be followed by JIS in/out character
;#
;#	-b	buffered output (default)
;#	-u	unbuffered output
;#	-m	dynamic input code recognition
;#	-c	print code name
;#	-v	print escape sequences used in JIS when used along with -c.
;#
;#$rcsid
;#-
;# Input Kanji code is recognized automatically if not supplied. 
;# Usually this is done only once, but it will be done on each input
;# line when dynamic recognition is specified.
;#
;# Output Kanji code is JIS by default.
;#
;# Output JIS code can be followed by kanji in and out characters.
;# Default is "BB" which means kanji sequence start with ESC-$-B and
;# end with ESC-(-B
;#
;# Example:
;#	pkf file	convert to JIS code
;#	pkf -j@J file	convert to JIS code ("ESC-$-@", "ESC-(-J")
;#	pkf -es file	convert EUC to SJIS
;#	pkf -me file	convert mixed code file to EUC
;#	pkf -mc file	convert to JIS and print orginal code on each line
;#
require 'jcode.pl';

$ocode = 'jis';
%codename  = ('j', 'jis', 's', 'sjis', 'e', 'euc');

;#
;# Option handling
;#
while (($_ = @ARGV[$[]) =~ s/^-(.+)/\1/ && shift) {
    next if $_ eq '';
    s/^[budmcv]// && ++$opt{$&} && redo;
    if (/^([jse]+)/) {
	($ocode, $icode) = @codename{split(//, reverse($1))};
	&jcode'jis_inout(split(//, $')) if $';
	next;
    }
    print "Usage:\n", $usage;
    exit(0);
}
$| = $opt{'u'} && !$opt{'b'};
($debug, $dynamic, $showcode, $showseq) = @opt{'d', 'm', 'c', 'v'};

if ($showcode && !$dynamic) {
    while (<>) {
	next unless $icode = &jcode'getcode(*_) || (eof && "ascii"); #'
	print $ARGV, ": " if @ARGV .. 0;
	print $icode;
	if ($showseq && $icode eq 'jis') {
	    local($jin, $jout) = &jcode'get_inout($_); #'
	    $jin =~ s/\e/ESC/g;
	    $jout =~ s/\e/ESC/g;
	    print ' [', $jin, ', ', $jout, ']';
	}
	print"\n";
	close ARGV;
    }
    exit 0;
}
	
while (<>) {
    $c = &jcode'convert(*_, $ocode), print($showcode ? "$c\t" : '', $_), next
	if $dynamic;
    $showcode || print, next if !@readahead && !/[\033\200-\377]/;
    push(@readahead, $_) unless $showcode;
    next unless $icode || ($icode = &jcode'getcode(*_));
    *convf = $jcode'convf{$icode, $ocode};
    printf STDERR "in=$icode, out=$ocode, f=$convf\n" if $debug;
    do convf(*_), print while $_ = shift(@readahead);
    do convf(*_), print while <>;
    last;
}
print @readahead;
exit $!;
