#!/usr/bin/perl
# $Id: capture.pl,v 1.8 2004/02/07 20:45:01 bd Exp $
# Takes an optional filename argument. Default is "usbcommands.txt"

my $USBREPLAYPATH = "./usbreplay";
my $USBREPLAYOPTS = "";
#my $USBREPLAYOPTS = "-x";

$CMDPATH = $ARGV[0] || "./usbcommands.txt";
my $CHAN = $ARGV[1] || "599.25";
my $FREQ = "27 e2";
my $B = "30";

if ($CHAN) {
    my ($mhz,$val);
    if ($CHAN =~ m/^(\d+\.\d+)/) {
	$mhz = $1;
    } else {
	die "Unsupported channel specification";
    }
    $val = int(622 + 16*$mhz + 0.5);
    $FREQ = sprintf("%02x %02x", $val>>8, $val&0xff);
    if ($mhz < 300) { $B = "90"; }
}

my $status = system("${USBREPLAYPATH} -i");
if ($status != 0) {
    die "Initialization process exited with status ".$status/256;
}

my $CMDPIPE = "/tmp/usbreplay.fifo";
system("mkfifo $CMDPIPE") unless -p $CMDPIPE;

my $pid = open PIPE, "|${USBREPLAYPATH} ${USBREPLAYOPTS}";
$pid or die "Couldn't start $USBREPLAYPATH: $!";
system("echo $pid > /tmp/usbreplay.pid");
select PIPE; $|=1; select STDOUT;

my $hcmd = *STDIN;
if ($CMDPATH ne '-') {
    open CMD, "<${CMDPATH}" or die "Couldn't open $CMDPATH: $!";
    $hcmd = *CMD;
}

my $line = undef;
my $prev_line = undef;
while (defined($line = <$hcmd>)) {
    # Allow some embedded Perl in the file for easier debugging.
    if ($line =~ m/^%/) {
	eval substr($line, 1);
    } elsif ($line =~ m/\$/) {
	eval 'print PIPE "' . $line . '"';
    } else {
	print PIPE $line;
    }
    $prevline = $line;
}

close $hcmd;
close PIPE;
