#! /usr/bin/perl
#
# A cheap-and-dirty (and probably inefficient) script that takes the output
# from USBSnoopy (as recorded by dbgview.exe) and cleans it up.  Specifically,
# it removes the line counts and time indexes that dbgview.exe slaps on,
# and displays an ASCII representation of the USB data packets.
#

while (<>) {
	chomp;

	s///g;
	s/^(\d+)\s+\S+\s//;
	$count= $1;

	s/\s+$//;

	if ( /^\s*([0-9a-f]{4}):$/ ) {
		$offsetval= $1;
		$offset= 1;
		next;
	} else {
		if ( $offset ) {
			s/^\s+//;
			@data= split(/\s+/, $_);
			printf("\t%04s: %s\n", $offsetval, &ascii_rep(@data));
		} else {
			printf("%s\n", $_);
		}

		$offset= 0;
	}
}

0;

sub ascii_rep {
	my (@ascii, $compact, $width);
	my ($i)= 0;

	@ascii= map {
		my ($dec)= hex($_);

		$compact.= $_;
		$compact.= ' ' if ($i%2);
		$i++;

		if ( $dec > 31 && $dec < 127 ) {
			sprintf("%c", $dec);
		} else {
			'.';
		}
	} @_;

	$width= 40-length($compact);
	return sprintf("%s%s %s", $compact, ' 'x${width}, join('', @ascii));
}
