#!/usr/bin/perl 

# Dump the correspondence between frame numbers and file positions in
# a ttyrec, with timestamps for good measure. With -f, also produce a
# hex dump of the terminal contents in each frame.

@args = ();
$opts = 1;
$join = 0;
$full = 0;
$to_script = 0;
$lastframe = -1;
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;
        } elsif ($1 eq "f") {
            $full = 1;
        } elsif ($1 =~ /-upto=(.*)$/) {
            $lastframe = $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 ($lastframe < 0 || $frame <= $lastframe) {
        $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";
            if ($full) {
                for ($pos = 0; $pos < length $data; $pos += 16) {
                    @dsub = unpack "C*", substr $data, $pos, 16;
                    printf "  %06x ", $pos;
                    for $chr (@dsub) {
                        printf " %02x", $chr;
                    }
                    print " " x (2 + 3 * (16 - @dsub));
                    for $chr (@dsub) {
                        if (defined $chr) {
                            if (0x20 <= $chr && $chr < 0x7F) {
                                printf "%c", $chr;
                            } else {
                                print ".";
                            }
                        }
                    }
                    print "\n";
                }
            }
        }
        $frame++;
        $tframe++;
    }

    close F;
}
