#!/usr/local/bin/perl

# 
# pstogif: EPS の該当部だけに GS を適用する．
# 
#     [1998/10/24] OSHIRO Naoki.
#     ・pstopnm から EPS 抽出機構だけを抜き出し．perl へ書き換え．
# 
#     $Log:$
#

require "getopts.pl";
&Getopts("Ss:tlc"); # S:smooth, s:scale, t:transparent, l:landscape, c:imagecrop

$filtertail = "raw";
$filterhead = "ppm";
$xsize = 0;
$ysize = 0;
$xres = "";
$yres = "";
$scale=1;
$smooth="";

$scale=$opt_s if $opt_s;
if ($opt_S) {
    $scale*=1.5;
    $tmp_scale=1.0/1.5;
    $smooth="| pnmscale $tmp_scale";
}

$file_stdin=0;
if ($#ARGV==-1) {
print STDERR "stdin\n";
    $psfile="/tmp/pnmtops2_$$.ps";
    open(F, ">$psfile");
    while (<>) {
	print F;
    }   
    close(F);
    $file_stdin=1;
} else {
    $psfile=$ARGV[0];
}

# default values: max image x and y sizes
# この値で生成画像の大きさが決まる．
$xmax = 100;
$ymax = 100;

# default values: x and y borders are 10% of x and y size
$xborder = "0";
$yborder = "0";

$bb = `grep "^%%BoundingBox" $psfile|head -1`;
unless (($llx,$lly,$urx,$ury)=$bb=~/%%BoundingBox: +(.+) +(.+) +(.+) +(.+)/) {
    print STDERR "Error: No BoundingBox: $psfile $bb\n";
    exit;
}
print STDERR "BoundingBox: $llx $lly $urx $ury\n";

$tmpsx = $urx - $llx;
$tmpsy = $ury - $lly;

# now re$BoundingBox llc and total size to take into account margin
$llx = $llx - $tmpsx * $xborder-.5;
$lly = $lly - $tmpsy * $yborder-1.5;
$urx = $urx + $tmpsx * $xborder;
$ury = $ury + $tmpsy * $yborder;
# compute image area size 
$sx = $tmpsx + 2 * $xborder * $tmpsx+1.5;
$sy = $tmpsy + 2 * $yborder * $tmpsy+2.5;

#$xres = $xmax *72/$sx;
#$yres = $ymax *72/$sy;
$xres=$yres=72*$scale;
$xres = ($xres>$yres)? $yres:$xres;
$yres = $xres;
print STDERR "x:$sx y:$sy res:$xres\n";
$xsize = $sx * $xres /72+0.5;
$ysize = $sy * $yres /72+0.5;
$xsize =~s/\.[^\.]+$//;
$ysize =~s/\.[^\.]+$//;

# adjust offsets
$llx = $llx - ($xsize *72/$xres - $sx)/2;
$lly = $lly - ($ysize *72/$yres - $sy)/2;
$pstrans = "$llx neg $lly neg translate";
#$pstrans = "showpage";

if ($opt_t) {$giftrans="| giftrans -t '#ffffff'";}
$midtrans="";
if ($opt_c) {$midtrans="$midtrans| pnmcrop";}
if ($opt_l) {$midtrans="$midtrans| pnmflip -r270";}
system "(echo $pstrans; cat $psfile; echo showpage)  | gs -sDEVICE=${filterhead}${filtertail} -sOutputFile=- -g${xsize}x${ysize} -r${xres}x${yres} -q - $midtrans $smooth | ppmquant 256 | ppmtogif $giftrans";
