#!/usr/bin/perl

use IO::File;
use POSIX qw(tmpnam);

# this program undoes the damages (un)intentionally done by Poseidon
#
# first pass:
#   acquire the actual image size
#
# second pass:
#   change bounding box to match image size
#   get rid of poseidon background
#   disable landscape
#   disable fittopage
#   change setpagesize to actual image size
#   set margins to 0

sub firstpass
{
  my $fn = shift(@_);
  my $infile;
  open(my $infile, $fn) || die("\n\ncan't open data file: $!\n");
  while (<$infile>) 
  {
    if (/^\d+ \d+ setsize/) # look for xxx yyy setsize
    {
      ($width, $height) = split(/ +/, $_); # extract the width and height
      print "definition found!\n";
      return;
    }
  }
  close $infile;
}

sub secondpass
{
  my $fn = shift(@_);
  my $infile;
  my $outname;
  my $outfile;
  do { $outname = tmpnam() }
    until $outfile = IO::File->new($outname, O_RDWR|O_CREAT|O_EXCL);
  open(my $infile, $fn) || die("\n\ncan't open data file: $!\n");
  while (<$infile>)
  {
    if (/^\%\%BoundingBox:/)
    {
      print "found BoundingBox, replacing it now\n";
#      print $outfile "\% original: $_";
      print $outfile "\%\%BoundingBox: 0 0 $width $height\n";
    }
    elsif (/^landscape/)
    {
      print "found landscape line, commenting it out\n";
      print $outfile "\% original: $_";
    }
    elsif (/^fittopage/)
    {
      print "found fittopage line, commenting it out\n";
      print $outfile "\% original: $_";
    }
    elsif (/^\d+ \d+ setpagesize/)
    {
      print "found setpagesize line, replacing sizes\n";
      print $outfile "\% original: $_";
      print $outfile "$width $height setpagesize\n";
    }
    elsif (/^\d+ \d+ \d+ \d+ setmargins/)
    {
      print "found setmargins line, replacing margins\n";
      print $outfile "\% original: $_";
      print $outfile "0 0 0 0 setmargins\n";
    }
    elsif (/^\(\\000P\\000o\\000s\\000e\\000i\\000d\\000o\\000n/)
    {
      print "found logo line, replacing with empty string\n";
      my $newstr;
      $newstr = $_;
      $newstr =~ s/^\([^\)]*\)/()/;
      print $outfile $newstr;
    }
    else
    {
      print $outfile $_;
    }
  }
  close $infile;
  close $outfile;
  rename($outname, $fn) || die("cannot rename $outname to $fn\n");
}

print "$#ARGV is the index of the last argument\n";

if ($#ARGV < 0)
{
  die("\nmust supply the filename as an argument\n");
}

firstpass($ARGV[0]);
print "width is $width, height is $height\n";

secondpass($ARGV[0]);

