#!/usr/athena/bin/perl

$/ = "";
$|=1;
$suc= 1;
while($suc){
	$suc = 0;
	open(S, $ARGV[0]) || ($suc=1);
	open(T, $ARGV[1]) || ($suc=1);
	open(SO, ">$ARGV[0]") || ($suc=1);
	open(TO, ">$ARGV[1]") || ($suc=1);
}
vec($sin, fileno(S), 1) = 1;
vec($tin, fileno(T), 1) = 1;
while(1) {
    if(select($sout=$sin, undef, undef, 0)){
	$n = sysread(S, $buf, 1);
	next unless $n >= 1;
	syswrite(TO, $buf, $n);

	&process($buf, 0);
    }
    elsif(select($tout=$tin, undef, undef, 0)){
	$n = sysread(T, $buf, 1);
	next unless $n >= 1;
	syswrite(SO, $buf, $n);

	&process($buf, 1);
	}
}


sub process {
    $data = shift;
    $stream = shift;

    $hex = unpack("H*", $data);
    if(($hex eq "7d") && ($esc[$stream] != 1)){
	$esc[$stream] = 1;
	return;
    }

    if($esc[$stream]){
	$esc[$stream] = 0;
	$data = pack("c", (ord($data) ^ 32));
	$hex = unpack("H*", $data);
    }
    elsif($hex eq "7e"){
	print "Frame on stream $stream: $packet[$stream]\n" if $packet[$stream];
	$packet[$stream] = "";
	$byte[$stream]  = 1;
	return;
    }

    $byte[$stream]++;
    if(($byte[$stream] >= 19) && ($byte[$stream] <= 22)){
	${destaddr[$stream]}[$byte[$stream]-19] = ord($data);
    }

    if($byte[$stream] == 22){
	print "Packet going to ", join(".", @{$destaddr[$stream]}), "\n";
    }

if(($byte[$stream] == 3) && ($hex ne "45")){
    print "-----Messed up packet on stream $stream\n";
}

    $packet[$stream] .= "$hex ";
}
