#!/usr/bin/perl
# 
# Copyright (C) Koji Nakamaru
#
# Author: Koji Nakamaru (nakamaru at gmail.com)
# Modified: Apr 30 2005
#   * changed the contact information.
# Created: Apr 20 2002
# Keywords: postscript, ghostscript, dvipdfm
#
# This file is part of dvipdfa.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2, or (at your option)
# any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with GNU Emacs; see the file COPYING.  If not, write to the
# Free Software Foundation, Inc., 59 Temple Place - Suite 330,
# Boston, MA 02111-1307, USA.
#

$gs = $ARGV[0];
$zcat = $ARGV[1];
$devw = $ARGV[2];
$fnamei = $ARGV[3];
$fnameo = $ARGV[4];
$fnamei =~ s|\\|/|g;
$fnameo =~ s|\\|/|g;

if ($zcat != "none") {
    open FI, "$zcat -f $fnamei|";
} else {
    open FI, "<$fnamei";
}
$llx = $lly = $urx = $ury = 0;
while (<FI>) {
    if (/^%/) {
	if (/^%%BoundingBox:\s*([0-9]+)\s+([0-9]+)\s+([0-9]+)\s+([0-9]+)/) {
	    $llx = $1;
	    $lly = $2;
	    $urx = $3;
	    $ury = $4;
	}
    } elsif (/^[^%]/) {
	last;
    }
}
close FI;
$llx -= 2;
$lly -= 2;
$urx += 2;
$ury += 2;
$w = $urx - $llx;
$h = $ury - $lly;
$s = ($w > $h) ? ($devw - 1) / $w : ($devw - 1) / $h;
$w0 = int($w * $s + 1);
$h0 = int($h * $s + 1);
$w1 = $urx;
$h1 = $ury;

if ($zcat != null) {
    system
	"$zcat -f $fnamei"
	. " | $gs -q -dBATCH -dNOPAUSE"
	. " -dDEVICEWIDTHPOINTS=$w0 -dDEVICEHEIGHTPOINTS=$h0"
	. " -sDEVICE=epswrite -sOutputFile=-"
	. " -c $s $s scale $llx neg $lly neg translate -f - -c quit"
	. " | $gs -q -dBATCH -dNOPAUSE"
	. " -dDEVICEWIDTHPOINTS=$w1 -dDEVICEHEIGHTPOINTS=$h1"
	. " -sDEVICE=pdfwrite -dPDFSETTINGS=/prepress -dCompatibilityLevel=1.2"
	. " -dAutoFilterGrayImages=false -dAutoFilterColorImages=false"
	. " -dGrayImageFilter=/FlateEncode -dColorImageFilter=/FlateEncode"
	. " -dUseFlateCompression=true -sOutputFile=$fnameo"
	. " -c $llx $lly translate 1 $s div dup scale -f - -c quit";
} else {
    system
	"$gs -q -dBATCH -dNOPAUSE"
	. " -dDEVICEWIDTHPOINTS=$w0 -dDEVICEHEIGHTPOINTS=$h0"
	. " -sDEVICE=epswrite -sOutputFile=-"
	. " -c $s $s scale $llx neg $lly neg translate -f $fnamei -c quit"
	. " | $gs -q -dBATCH -dNOPAUSE"
	. " -dDEVICEWIDTHPOINTS=$w1 -dDEVICEHEIGHTPOINTS=$h1"
	. " -sDEVICE=pdfwrite -dPDFSETTINGS=/prepress -dCompatibilityLevel=1.2"
	. " -dAutoFilterGrayImages=false -dAutoFilterColorImages=false"
	. " -dGrayImageFilter=/FlateEncode -dColorImageFilter=/FlateEncode"
	. " -dUseFlateCompression=true -sOutputFile=$fnameo"
	. " -c $llx $lly translate 1 $s div dup scale -f - -c quit";
}
