#!/usr/bin/perl

use integer;
$WIDTH = 363; # maximum width of the composed picture
$width = 10;  # width of the board
$height = 6;  # height of the board

%palat = ();

for ($n = 0; <>; $n++) {
    if (/^([a-z]{$width})$/o) {
	$pala = $1;
	for ($i = 1; $i < $height; $i++) {
	    $_ = <>;
	    /^([a-l]{$width})$/o || die;
	    $pala .= $1;
	}

	$pala =~ tr/a-l/\000\103\142\173\221\244\265\306\325\343\361\376/;
	$pala2 = &flipx ($pala);

	exists $palat{$pala} ||
	    exists $palat{$pala2} ||
		exists $palat{&flipy ($pala)} ||
		    exists $palat{&flipy ($pala2)} ||
			($palat{$pala} = $n);
    }
}

@palat = keys (%palat);
$num = $#palat + 1;
$rows = ($num * ($width + 1) + $WIDTH - 1) / $WIDTH;
$x = (($num + $rows - 1) / $rows) * ($width + 1);
$y = $rows * ($height + 1);

@rows = ();
for ($row = 0; $row < $y; $row++) {
    $rows[$row] = ($row % ($height + 1)) == $height ? "\377" x $x : "";
}
$row = 0;

warn "$num pieces, $rows rows, $x×$y pixels\n";

print "P5\n", $x, " ", $y, "\n", 255, "\n";
for $p (@palat) {
    if (length ($rows[$row]) >= $x) {
	$row += $height + 1;
    }
    for ($i = 0; $i < $height; $i++) {
	$rows[$row + $i] .= (substr $p, $i * $width, $width) . "\377";
    }
}

for ($pad = $x - length ($rows[$row]); $row < $y; $row++) {
    $rows[$row] .= "\377" x $pad;
}

print @rows;

sub flipx
{
    local ($p) = @_;
    local ($i);

    $p =~ s/(.)(.)(.)(.)(.)(.)(.)(.)(.)(.)/$10$9$8$7$6$5$4$3$2$1/g;
    return $p;
}

sub flipy
{
    local ($p) = @_;
    local ($i);

    $p =~ s/^(..........)(..........)(..........)(..........)(..........)(..........)$/$6$5$4$3$2$1/g;
    return $p;
}
