#!/usr/bin/perl

undef $/;
$rawdata=<>;

$splitstring=pack("H16a*","0D0A20202020201B", "l0370");

# The data is written in 13 vertical columns, from the bottom to the top.
# It starts at the lower-left, moves to the upper left, and then goes
# back to the lower left, slightly offset to the right.  Each vertical
# column is 16 pixels wide, and each pixel occupies one bit.

@seg=split /$splitstring/,$rawdata;

# The first bit is some sort of header that we do not understand or use.
shift @seg;

foreach $segment (@seg)
{
    $bar=unpack("B*",$segment);

    # Wrap after 16 pixels
    $bar=~s/(.{16})/$1\n/g;

    # Add spaces to turn it into a pbm
    $bar=~s/(.)/$1 /g;

    # and write it to an array, @lines,, where we will append the
    # subsequent columns
    @templines=split /\n/,$bar;
    for ($i=0; $i<=$#templines; $i++)
    {
	$lines[$i].=$templines[$i];
    }
}

# There's junk at the top, but only in the first column.  Perhaps it's
# meaningful non-graphical information we just don't understand.
for ($i=0; $i<5; $i++)
{
    pop @lines;
}

# There's lots of white space around the edges, obviously, as the screen
# is only 200x200.  We could get rid of it, but I don't really see a need.
# You can always crop it later if you want to.

print "P1 240 246\n";
print "# Created from a Metex DSO screen dump by metex2pbm.\n";
print "# see http://www.consistent.org/metex-dso/ for more information\n";

# Every third line apparently needs to be discarded.  If you look at them,
# they look quite strange, like an average of the line below and the line
# above.  I don't really understand what's going on there, but the Metex
# Windows software seems to simply throw them away, so I do the same here.
while ($#lines >= 0)
{
    @l = (pop @lines, pop @lines, pop @lines);
    print "$l[0]\n$l[1]\n";
}
