eval 'exec perl -S $0 ${1+"$@"}'
if 0;
#! /usr/local/bin/perl
#	@(#)wch2hex 00-05-12
#
#	磻ɥ饯򣱣ʿѴ
#	(C) Copyright 1994-2000 by Personal Media Corporation
#
#	()	L''		0xa3c1
#		L""		0xa3c1, 0xa3c2, 0x0000
#		L""+	0xa3c1, 0xa3c2
#
#	 ʸ EUC ɤǤȤ
#
#	ץ
#	-e	EUC ɤѴ (ǥե)
#	-t	TRON ʸɤѴ
#
$usage = 'usage: wch2hex [{-e|-t}] [-o outfile] [infile]';

# ץΥǥե
$infile = "-";	# ɸϤɤ߹
$outfile = "-";	# ɸϤؽ񤭽Ф
$code = "-e";	# EUC ɤѴ

# ޥɥ饤β
$para = "";
foreach ( @ARGV ) {

	if ( $para eq "" ) {
		switch: {
		  if ( /^-[et]/ )	{ $code = $_; last; }
		  if ( /^-o/ )		{ $para = $_; last; }
		  if ( /^-.*/ )		{ print STDERR "$usage\n"; exit(1); }

		  if ( $infile eq "-" )	{ $infile = $_; }
		  else			{ print STDERR "$usage\n"; exit(1); }
		}
	} else {
		if ( $para =~ /-o/ )	{ $outfile = $_; }
		$para = "";
	}
}

open(IN, "$infile")	|| die "can not open $infile\n";
open(OUT, ">$outfile")	|| die "can not open $outfile\n";

$srch = "(L\"[^\"]*\"\\+?)|(L'[^']{1,2}')";

while ( <IN> ) {

	# Ѵоݤʸ󤬤ַ֤
	while ( ($lstr) = /($srch)/ ) {

		# ѴоݤʸФ
		($str) = $lstr =~ /^L["'](.*)["']\+?$/;

		# ѴоݤʸʸѴ
		@hex = (); $n = 0; $i = 0;
		while ( $ch = substr($str, $i++, 1) ) {
			$h = ord($ch);
			if ( ($h & 0x80) == 0 || $hex[$n] != 0 ) {
				$hex[$n++] += $h;
			} else {
				$hex[$n] = $h << 8;
			}
		}

		# L"..." ηʤ顢Ǹ˥̥(0)ɲ
		if ( $lstr =~ /^L".*"$/ ) {
			$hex[$#hex + 1] = 0;
		}

		# ʸѴʸؤѴ
		$hexstr = "";
		for ( $i = 0; $i <= $#hex; $i++ ) {
			if ( $code eq "-t" ) {
				# TRON ʸɤѴ
				$hex[$i] &= 0x7f7f;
			}

			# ޶ڤʸѴ
			$hexstr .= sprintf(", 0x%04x", $hex[$i]);
		}
		$hexstr = substr($hexstr, 2);

		# Ѵʸɤ֤
		s/$srch/$hexstr/;
	}

	print OUT $_;
}

close(IN);
close(OUT);

exit(0);
