#!/usr/bin/perl -w
use strict;

#
# Read and ignore the binary PPM header.
#
my $header = <STDIN>;
die "not a RAWBITS PPM file (magic != 'P6')\n" unless ($header =~ '^P6');
$header =~ s/#.*$//;	# strip comments
until ($header =~ /^P6\s+\d+\s+\d+\s+\d+\s+/) {
    $header .= <STDIN>;
    $header =~ s/#.*$//;	# strip comments
}

#
# This script only works on 4-color grayscale images which (a) use
# 0, 128, 160, and 255 as the 4 RGB values and (b) have the same
# values for R, G, and B (since G and B are ignored).
#
my %colormap = (0 => '00', 128 => '01', 160 => '10', 255 => '11');

my $pixels;
while (read(STDIN, $pixels, 12)) {
    my @pixels = (unpack "C12", $pixels)[0,3,6,9];
    print(pack('b8', join('', map { $colormap{$_} } @pixels)));
}

