#!/usr/bin/perl -w
use strict;

our $nbits = 16; # need to adjust unpack statement as well
our $stamp = qx/LC_TIME=C date/;

print << "EOC";
\$date
    $stamp
\$end
\$version
    memdump2vcd.pl
\$end
\$timescale
EOC

print defined $ENV{XDIV} ? $ENV{XDIV} . " ns" : "  1 ps";
print "\n";
print "\$end\n";
our $i;

for($i=0; $i<$nbits; $i++) {
    printf("\$var reg 1 %x %x \$end\n", $i, $i);
}

print << 'EOC';
$upscope $end
$enddefinitions $end
EOC
    ;

our $time = 0;
our $prev = undef;
our $laststamp = -1;
while (read STDIN, my $bits, 2) {
    $bits = unpack ("S", $bits);
    my $diff = defined $prev ? $prev ^ $bits : 0xffff;
    for($i=0; $i<$nbits; $i++) {
	if ($diff & (1 << $i)) {
	    if ($time != $laststamp) {
		printf("#%d\n", $time);
		$laststamp = $time;
	    }
	    printf("%d%x\n", ($bits & (1<<$i)) ? 1 : 0, $i);
	}
    }
    $prev = $bits;
    $time++;
}
