#!/usr/bin/perl 

# Dump the correspondence between frame numbers and file positions
# in a ttyrec, with timestamps for good measure.

@args = ();
$opts = 1;
$join = 0;
$to_script = 0;
foreach $i (@ARGV) {
    if ($opts and $i =~ /^-(.*)/) {
	if ($1 eq "-") {
	    $opts = 0;
	} elsif ($1 eq "j") {
	    $join = 1;
	} elsif ($1 eq "s") {
	    $to_script = 1;
	} else {
	    warn "unrecognised option '-$1'\n";
	}
    } else {
	push @args, $i;
    }
}

if (!defined $args[0]) {
    print STDERR "usage: ttydump <file> [<file>...]\n";
    # If called with no arguments, we assume we're being _asked_ to
    # print the usage statement, so we do so and exit with no
    # error. If called with one argument, we have no remaining
    # choice but to assume the user is mistaken.
    exit (defined $args[0]);
}

$tframe = 0;

foreach $file (@args) {
    open F, "<$file" or die "$0: unable to open '$file'\n";

    $frame = 0;

    while (1) {
	$hdr = "";
	$hgot = read F, $hdr, 12;
	last if $hgot == 0; # clean EOF
	die "$0: unexpected EOF in '$file' frame header\n" if $hgot < 12;
	@hdrvals = unpack "VVV", $hdr;
	$dlen = $hdrvals[2];
	$data = "";
	$posdata = sprintf "offset 0x%x len 0x%x", (tell F), $dlen;
	$posdata = "$file " . $posdata if $join;
	$timestamp = sprintf "%d.%06d", $hdrvals[0], $hdrvals[1];
	$dgot = read F, $data, $dlen;
	die "$0: unexpected EOF in '$file' frame data\n" if $dgot < $dlen;
	if ($join) {
	    $location = "$tframe";
	} else {
	    $location = "$file:$frame";
	}
	if ($to_script) {
            print $data;
        } else {
            print "$location:$timestamp:$posdata\n";
        }
	$frame++;
	$tframe++;
    }

    close F;
}
