#!/usr/bin/perl -w

foreach $file (@ARGV) {
	open (INPUT, $file) or print (STDERR "$file: $!\n");
	$line = 0;
	$time = 0;
	@frame = ();
	print ("; $file\n");
	while (<INPUT>) {
		chomp ($_);
		if (substr ($_, 0, 1) eq "#") {
			next;
		} elsif (substr ($_, 0, 1) eq "@") {
			$time = substr ($_, 1);
			chomp ($time);
			if ($line != 0) {
				print (STDERR "$file: frame too short ($line)\n");
				$line = 0;
				@frame = ();
			}
		} else {
			if (length ($_) >= 18) {
				$frame[$line++] = $_;
			}
		}
		if ($line == 8) {
			if ($time == 0) {
				print (STDERR "$file: time is zero, assuming 100ms\n");
				$time = 100;
			}
			printf (".db 0x%02x, 0x%02x", $time % 0x100, $time / 0x100);
			foreach $frameline (@frame) {
				$byte1 = 0;
				$byte2 = 0;
				$byte3 = 0;
				for ($bit = 0; $bit <= 7; $bit++) {
					if (substr ($frameline, $bit, 1) ne "0") {
						$byte1 |= 2**$bit;
					}
				}
				for ($bit = 8; $bit <= 9; $bit++) {
					if (substr ($frameline, $bit, 1) ne "0") {
						$byte2 |= 2**($bit - 5);
					}
				}
				for ($bit = 10; $bit <= 17; $bit++) {
					if (substr ($frameline, $bit, 1) ne "0") {
						$byte3 |= 2**($bit - 10);
					}
				}
				printf (", 0x%02x, 0x%02x, 0x%02x", $byte1, $byte2, $byte3);
			}
			print ("\n");
			$line = 0;
			$time = 0;
			@frame = ();
		}
	}
	print ("\n");
	close (INPUT);
}
