#!/usr/bin/perl -w

use strict;

# modified for windows  11/14/02

# for ghostscript
my $gs = 'c:\local\gs\gs7.05\bin\gswin32.exe';
my $output_device="tiff24nc";
my $output_ext = "tiff";

#for final image
my $final_ext = "png";
#$final_ext = "gif";


my $rotate = 0; # need to rotate for landscape slides.
my $size ;
my $resolution ;
my $roll;

	
my $file;

if($ARGV[0])
{
	$file = $ARGV[0];
}
else
{
	usage();
}

unless(-f $file)
{
	die "$file not found\n";
}

open(PS,"<$file");

while(1)
{
	my $line = <PS>;
	unless($line =~ m/^%/)
	{
		close(PS);
		last;
	}
	if($line =~ m/Orientation: Landscape/)
	{
		$rotate = 1;
	}
}

if($rotate)
{
	$size = "768x1024"; # pixels to crop to (rotated 90)
	$resolution = "91"; # DPI was 91 for unix
	$roll = "+52-20";
}
else
{
	$size = "1024x768"; # pixels to crop to (rotated 90)
	$resolution = "70"; # DPI
	$roll = 214;# to center the image
}


my ($fname) = $file =~ m/^(.*)\.\w+/;

if($fname =~ m|/|)
{
	($fname) = $fname =~ m|/([^/]*)$|;
}

#my $gs_options = "-dBATCH -dNOPAUSE -dDOINTERPOLATE -dGraphicsAlphaBits=4 -dTextAlphaBits=4";
my $gs_options = "-dBATCH -dNOPAUSE -dDOINTERPOLATE -dTextAlphaBits=4";
if($size)
{
	$gs_options .= " -g$size ";
}
if($resolution)
{
	$gs_options .= " -r$resolution ";
}

print STDERR "Rendering PS ... ";

my $gs_command = "$gs  $gs_options -sDEVICE=$output_device -sOutputFile=$fname-%02d.$output_ext";

`$gs_command $file`;

print STDERR "Converting ... ";

#my $files = `ls -1 $fname-*.$output_ext`;

my $i = 1;

while(1)
{
	my $f = $fname."-".sprintf("%02i",$i).".".$output_ext;

	unless(-f $f)
	{
		last;
	}

	print STDERR "$i ";
	$i++;
	my ($new_name) = $f =~ m/^(.*)\.$output_ext$/;
	
	if($rotate)
	{
		`convert -compress none $f -rotate -90 -roll $roll $final_ext:$new_name.$final_ext`;
	}
	else
	{
		`convert -roll +$roll+0 -compress none $f $final_ext:$new_name.$final_ext`;
	}
	
	if(-f "$new_name.$final_ext" )
	{
		unlink($f);
	}
}
print STDERR "\n";

sub usage {

	die "usage: $0 file.ps\n";
}
