#!/usr/bin/perl -w

#
# ps2png
# convert a PS file to a PNG file
# 
# usage: ps2png [ps file] -r [rotation] -s [scale] -v -eps
#
# -r must be 90, 180, or 270
# -s has decimal form from 0 to 1
# -v to view the file (requires xv)
# -eps for encapsulated postscript files
#
# if input is file.ps then output will be file.png
#

use File::Basename;
use strict;

# gather input variables and check usage

my $usage = "Usage: ps2png [postscript file] -r [90,180,270] -s [scale] -v -eps";
my $in = $ARGV[0] or die "Error: input file not listed\n$usage\n";

my $r = '';
my $s = 1.0;
my $v = '';
my $ps = 'ps';

while (@ARGV) {
	my $arg = shift @ARGV;
	$r = shift @ARGV if ($arg =~ /^-r/);
	$s = shift @ARGV if ($arg =~ /^-s/);
	$v = 1 if ($arg =~ /^-v/);
	$ps = 'eps' if ($arg =~ /^-eps/);
}

if ($r) { die "Error: non-standard rotation '$r'\n$usage\n" unless ($r =~ /^(90|180|270)$/); }

# find base string

my ($out,$path,$suffix) = fileparse($in,".$ps");
$out = "$path$out";

# generate PPM file from PS file

my $cmd = "gs -dSAFER -dBATCH -dNOPAUSE -dTextAlphaBits=4 -dGraphicsAlphaBits=4 -sOutputFile=- -sDEVICE=pnmraw -r200 -q $out.$ps";

# rotate file if so desired

$cmd .= " | pnmflip -r$r" if ($r);

# crop, re-pad, and save file

$cmd .= " | pnmcrop | pnmpad -white -left=25 -right=25 -top=25 -bottom=25 | pnmscale $s | pnmtopng > $out.png"; 

system($cmd) == 0 or die "Error executing 'ps2png' system command\n$!\n";

if ($v) {
	$cmd = "xv $out.png &";
	system($cmd) == 0 or die "Error executing 'xv' system command\n$!\n";
}

