#!/usr/bin/perl

#strip the header and check the incoming data is what we can work with.

$line=<>;
die("Sorry I can only deal with rawbits ppm right now") if ($line !~ /^P6$/);
while ($line = <>) { last if (($line !~ /^#/) && ($line !~ /^$/)); }
#die("Sorry I need the image to be 128x128 already") if ($line !~ /^128 128$/);
while ($line = <>) { last if (($line !~ /^#/) && ($line !~ /^$/)); }

# trying averaging code instead
#die("Sorry I need the image to have a depth of 31") if ($line !~ /^31$/);

#slurp in the rest to $file

{
$/=undef;
$file=<>;
}

$length=length($file);

for($i=0;$i<$length;) {
  $byte1=substr $file,$i,1;
  $byte1=int(ord($byte1)/8 + 0.0);
  $byte2=substr $file,$i+1,1;
  $byte2=int(ord($byte2)/4 + 0.0);
  $byte3=substr $file,$i+2,1;
  $byte3=int(ord($byte3)/8 + 0.0);

  print pack("B16",scalar(reverse(unpack("b5",chr($byte1)))).scalar(reverse(unpack("b6",chr($byte2)))).scalar(reverse(unpack("b5",chr($byte3)))));

  $i+=3;
}
