#! /usr/bin/perl

$| = 1;
$np = 0;

$in = shift or die("bad arg");
open IN, $in or die("open `$in': $!");
while (<IN>) {
  $np = $1, last if /^%%Pages:\s*(\d+)\s*$/;
}
die("no pages") unless $np;

sub sel($) { sprintf("tmp.sel.%05d.ps", $_[0]); }
sub image($) { sprintf("img%05d.png", $_[0]); }

END {
  for ($i = 1; $i <= $np; $i++) {
    unlink(sel($i));
  }
}

print "converting...";
for ($p = 1; $p <= $np; $p++) {
  print " [";
  system qw"psselect -q -p", $p, $in, sel($p) and die("psselect: $?");
  print "$p";
  system qw"convert
    -density 300 -antialias -geometry 600x800 -rotate -90
    -bordercolor black -border 0x17",
    sel($p), image($p) and die("convert: $?");
  print "]";
  unlink(sel($p));
}
print "\n";
