$header = 0;
if ($ARGV[0] =~ /-h/) { $header = 1; shift; }

@array = ();
while (<>) {
  @bytes = split;
  next if !@bytes;
  @line = ();
  foreach (@bytes) {
	@bits = reverse split //;
	$value = 0;
	for ($i = 0; $i < @bits; $i++) {
	  if ($bits[$i] == 1) {
		$value |= 2**$i;
	  } elsif ($bits[$i] != 0) {
		die;
	  }
	}
	push @line, $value;
  }
  push @array, [@line];
}


print "# set_address = 0;\n# BASE = hex;\n" if $header;

$w = @{@array[0]}/2;
$h = @array/2;

for ($y = 255; $y >= 0; $y--) {
  if ($y < $h) {
	$yp = $y + $h;
  } elsif ($y >= 256-$h) {
	$yp = ($y + $h) % 256;
  } else {
	$yp = -1;
  }
  for ($x = 31; $x >= 0; $x--) {
	if ($yp == -1) { print "00 "; next; }
	if ($x < $w) {
	  $xp = $x + $w;
	  printf "%02X ", $array[$yp][$xp];
	} elsif ($x >= 32-$w) {
	  $xp = ($x + $w) % 32;
	  printf "%02X ", $array[$yp][$xp];
	} else {
	  print "00 ";
	}
  }
  print "\n";
}
