#!/usr/bin/perl
$^W=1;
use strict;

use File::Basename;

# vi(1) :se tabstop=4

# ascii2hex convert ASCII to hex
# hex2ascii convert hex to ASCII

$ENV{LC_ALL}='C'; # use ASCII encoding

my $prog_name=basename($0);

if($prog_name eq 'ascii2hex'){
	local $/=\1; # (logically) read byte at a time
	while(<>){
		printf("%02x",ord);
	};
}elsif($prog_name eq 'hex2ascii'){
	local $/=undef; # slurp mode
	$_=<>;
	defined($_) or exit 0;
	die("$prog_name: non-hex letters are disallowed, aborting") if /[G-Zg-z]/;

	# split at all non-hex character sequences
	my @hex=split(/[^0-9A-Fa-f]+/,$_,-1);
	my $ascii=''; # store up ASCII results
	while(@hex){
		$_=pop(@hex);
		next if /\A\z/; # skip empty strings
		while($_ ne ''){
			# We process right to left,
			# because if we have sequence of odd number of hex digits,
			# we want to interpret the first hex digit as having an implied
			# leading 0, and the remainder as pairs of hex digits,
			# if we didn't do it that way we'd be misaligned on our pairing.
			/\A(.*?)(.{1,2})\z/;
			$_=$1;
			my $hex=$2;
			$ascii=chr(hex($2)) . $ascii;
		}
	}
	print($ascii);
}else{
	die("$0: should be invoked as ascii2hex or hex2asii, was invoked as $0, aborting");
};
