#!/usr/bin/perl

use GD;

my $palette = $0;
$palette =~ s/[^\/]+$/palette.ppm/;


while ( my $file = shift @ARGV )
  {
  if ( $file =~ /\.pdf$/ )
    { open IN, "pdftops -f 1 -l 1 -paper match $file - | convert -resize 96x144 -type TrueColor PS:- JPG:- | djpeg -pnm -map $palette -dither ordered | pnmtopng 2>/dev/null |"; }
  else { open IN, "convert -resize 96x144 -type TrueColor $file JPG:- | djpeg -pnm -map $palette -dither ordered | pnmtopng 2>/dev/null |"; }
  my $in = join( '', <IN> );
  close IN;

  $image = GD::Image->new( $in );

  $k = 3;
  @px = ( );

  $left = int( ( 96 - $image->width ) / 2 );
  $right = 96 - $image->width - $left;
  $top = int( ( 144 - $image->height ) / 2 );
  $bottom = 144 - $image->height - $top;

  $file =~ s/\..+?$/_6090.t2b/;
  open OUT, "> $file";

  for ( $i = - $top; $i < 144 - $top; $i ++ )
    {
    for ( $j = - $left; $j < 96 - $left; $j ++ )
      {
      $px[$k --] = ( ( $i >= 0 and $i < $image->height and $j >= 0 and $j < $image->width ) ? $image->getPixel( $j, $i ) : 3 );
      if ( $k < 0 )
        {
        # this line can be here because 4 divides 96
        print OUT chr( $px[0] + 4 * $px[1] + 16 * $px[2] + 64 * $px[3] );
        $k = 3;
        }
      }
  
    }

  close OUT;
  }
