#!/usr/bin/perl
$task = $ARGV[0];
shift;

if ($task eq "usbsnoop-iso") {
    while(<>) {
	chomp;
	if (/IsoPacket/) {
	    $iso = 1;
	} elsif ($iso && /[0-9a-f]{8}: (.+)/) {
	    $bytes = $1;
	    foreach $byte (split(/ /, $bytes)) {
		print(chr(hex($byte)));
	    }
	} else {
	    $iso = 0; }
    }
} elsif ($task eq "usbsnoop-iso-sync") {
    while(<>) {
	chomp;
	if (/IsoPacket/) {
	    $iso = 1;
	} elsif ($iso && /[0-9a-f]{8}: (.+)/) {
	    $bytes = $1;
	    foreach $byte (split(/ /, $bytes)) {
		$packet .= chr(hex($byte));
	    }
	} else {
	    if (substr($packet, 0, 6) eq "\xff\xff\x00\xc4\xc4\x96") {
		$header_found = 1;
		if ($image_len > 0) {
		    print "\xff" x (320*200*3 - ($image_len % (320*200*3)));
		    $image_len = 0;
		}
		$packet = substr($packet, 16*4);
	    }
	    if ($header_found) {
		$image_len += length($packet);
		print $packet;
	    }
	    $packet = "";
	    $iso = 0;
	}
    }
} elsif ($task eq "usbsnoop-raw") {
    while(<>) {
	chomp;
	if (/[0-9a-f]{8}: (.+)/) {
	    $bytes = $1;
	    foreach $byte (split(/ /, $bytes)) {
		print(chr(hex($byte)));
	    }
	}
    }
} elsif ($task eq "usbsnoop-annotate") {
    while(<>) {
	chomp;
	$line = $_;
	chomp($line);
	print $line;
	print " ";
	if ($line =~ /[0-9a-f]{8}: (.+)/) {
	    $bytes = $1;
	    foreach $byte (split(/ /, $bytes)) {
		$chr = chr(hex($byte));
		if ($chr =~ /[[:print:]]/) {
		    print $chr;
		} else {
		    print "."; 
		}
	    }
	}
	print "\n";
    }
} elsif ($task eq "usbsnoop-annotate2") {
    my $dir = "";
    while(<>) {
	chomp;
	$line = $_;
	chomp($line);
#	print $line . "\n";
	if ($line =~ /going down/) {
	    $dir = ">";
	} elsif ($line =~ /coming back/) {
	    $dir = "<";
	} elsif ($line =~ /[0-9a-f]{8}: (.+)/) {
	    $bytes = $1;
	    print "$dir $line \"";
	    foreach $byte (split(/ /, $bytes)) {
		$chr = chr(hex($byte));
		if ($chr =~ /[[:print:]]/) {
		    print $chr;
		} else {
		    print "."; 
		}
	    }
	    print "\"\n";
	}
    }
} elsif ($task eq "log-pnm") {
    print "P6\n848 585\n255\n";
    while(<>) {
	chomp;
	if(/bulk read returned [0-9]+, bytes: ([^\"]+)/) {
	    $bytes = $1;
	    foreach $byte (split(/ /, $bytes)) {
		print(chr(hex($byte)));
	    }
	}
    }
} elsif ($task eq "usbmon") {
    $prev_time = 0;
    while (<>) {
	chomp;
	@cols = split(/ /);
	$time = $cols[1];
	my $delta = ($time - $prev_time) / 1000.0;
	printf("%9.0f", $delta);
	for (my $i = 2; $i < $#cols + 1; $i++) {
	    print(" " . $cols[$i]);
	}
	print("\n");
	$prev_time = $time;
    }
} else {
    print "unknown task\n";
}
