#!/usr/bin/perl
# ps2gif.pl
#
# THIS FILE IS COPYRIGHT 1994 BY TELENOR RESEARCH, NORWAY
#
#                    ALL RIGHTS RESERVED.
#
# For rights granted to the public see the COPYRIGHT file
#

# Usage		: ps2gif [options] <psfiles>
# Programmer	: Ole Gunnar Westgaard (olew@ifi.uio.no/olew@nta.no)

# This script is based upon several versions of ps2gif scripts, none of
# which worked like I wanted them to. There are a few major bugfixes also.

# Script fixes:
#	Now supports .eps ->.gif conversion
#	Better handling of colors, since gs doesn't do good 8-bit
#	Variable dpi setting allowed
#	Better resolution, the picture is zoomed, and then anti-alias shrinked
#	Can take more than one psfile at a time
#	User-definable transparent color in the resulting gif
#	Also works as a ps->ppm, should look good too

#   -   Since the quality is better the script needs more memory and time.
#   -   This script does not use a temporary directory.

# Based on scripts by:
#	Doug Crabill
#	Jon Stephenson von Tetzchner
#	Jan Rygh

###############################################################################
# Defaults

$bits		=8;
$xdpi		=96;
$ydpi		=96;
$colors		=256;
$x		=0;
$y		=0;
$xy		=0;
$renamed	=0;
$transparent	="";
$size		="";
$crop		=0;
$margin		=0;
$debug		=0;
$quiet		=0;

###############################################################################
# Read options

if (!(@ARGV)) {&help;}

while (@ARGV[0]=~/^-/) {
 $p=shift;
    if ($p eq "-gif")    { $bits= 8; }
 elsif ($p eq "-pnm")    { $bits=24; }
 elsif ($p eq "-t")      { $transparent="1,1,1"; }
 elsif ($p eq "-tc")     { $transparent=shift; }
 elsif ($p eq "-x")      { $x=shift; $xy=0; }
 elsif ($p eq "-y")      { $y=shift; $xy=0; }
 elsif ($p eq "-xy")     { $x=shift; $y=shift; $xy=1; }
 elsif ($p eq "-xdpi")   { $xdpi=shift; }
 elsif ($p eq "-ydpi")   { $ydpi=shift; }
 elsif ($p eq "-dpi")    { $xdpi=shift; $ydpi=$xdpi; }
 elsif ($p eq "-crop")   { $crop=1; }
 elsif ($p eq "-margin") { $margin=shift; }
 elsif ($p eq "-colors") { $colors=shift; }
 elsif ($p eq "-debug")  { $debug=1; $quiet=0; }
 elsif ($p eq "-q")      { $debug==0 && ($quiet=1); }
 elsif ($p eq "-help")   { &help; }
 else                    { &warning("Unknown switch $p"); }
}

if (!(@ARGV)) {&helpf;}

###############################################################################
# djf: Append NETPBM directory to path, partly so filters invoked by this
# script can be found, but also because ppmtogif invokes other NETPBM 
# programs without specifying absolute pathnames

if (-d "/usr/local/bin")
{
 local($path) = "/usr/local/bin:$ENV{'PATH'}";
 $ENV{'PATH'} = "$path";
}

###############################################################################
# Set sizes and scaling

if ($xy) {
 $size="pnmscale -xysize $x $y";
} else {
 if ($x) {
  if ($y) {
   $size="pnmscale -xsize $x -ysize $y";
  } else {
   $size="pnmscale -xsize $x";
  }
 } else {
  if ($y) {
   $size="pnmscale -height $y";
  }
 }
}

###############################################################################
# Defines that can go outside the loop

 $between="";
 if ($crop)    {	$between=$between."|pnmcrop "; }
 if ($size)    {	$between=$between."|$size "; }
 if ($margin)  {	$between=$between."|pnmmargin $margin "; }
 if ($bits==8) {	$between=$between."|ppmquant $colors "; }

###############################################################################
# Main loop

while (@ARGV) {
 $file=shift;
 $base=$file;
 if (!(-e $base)) {&warning("$file doesn't exist!");} else {# No such file
  if (!($base=~s/\.ps//i)) {
   if ($base=~s/\.eps//i) {
    $renamed=1;
    &execute("mv $file $base.ps");
   } else {
    &error("$file is not a PostScript file!");
   }
  }

  if (!$quiet) {
   if ($bits==8)   {print STDERR "ps2gif: $file -> $base.gif\n";}
   else            {print STDERR "ps2gif: $file -> $base.pnm\n";}
  }

  #############################################################################
  # Convert ps -> ppm , use 24 bit double size scaling

  if ($debug) {
   print STDERR "ps2gif: Debug: /usr/local/bin/gs -dNODISPLAY /usr/local/lib/ghostscript/pstoppm.ps\n";
   $GSPID=open(GS,"| /usr/local/bin/gs -dNODISPLAY /usr/local/lib/ghostscript/pstoppm.ps 1> /dev/null");
    print STDERR "ps2gif: Debug: $xdpi $ydpi ppmsetdensity\n";
    print GS "$xdpi $ydpi ppmsetdensity\n";
    print STDERR "ps2gif: Debug: ($base) ppm24run\n";
    print GS "($base) ppm24run\n";
   close(GS);
  } else {
   $GSPID=open(GS,"| /usr/local/bin/gs -dNODISPLAY /usr/local/lib/ghostscript/pstoppm.ps 1> /dev/null 2> /dev/null");
    print GS "$xdpi $ydpi ppmsetdensity\n";
    print GS "($base) ppm24run\n";
   close(GS);
  }

  if ($renamed>0) { &execute("mv $base.ps $file"); }

  #############################################################################
  # Do general processing of the file before we get into specializing

  &execute("cat $base.ppm $between > $base.2.ppm");

  if ($bits==8) {
 
   ############################################################################
   # Convert to gif, treat transparent and other things

   if ($transparent ne "") {
    $togif="ppmtogif -transparent $transparent ";
   } else {
    $togif="ppmtogif";
   }
   &execute("$togif $base.2.ppm > $base.gif");

   if (!$debug) {
    &execute("rm $base.ppm $base.2.ppm");
   }
  } else {

   ############################################################################
   # Rename the work to a pnm file

   &execute("mv $base.2.ppm $base.pnm");
   if (!$debug) {
    &execute("rm $base.ppm");
   }
  }
 
 }
}

###############################################################################
# Functions and procedures

sub warning {
  local($txt)=@_;
  print STDERR "ps2gif: WARNING: $txt\n";
}

sub error {
  local($txt)=@_;
  print STDERR "ps2gif: ERROR: $txt\n";
  exit 1;
}

sub execute {
 local($txt)=@_;
 if ($debug) {
  print STDERR "ps2gif: Executing \"$txt\"\n";
  system($txt);
 } else {
  system("($txt)2>/dev/null");
 }
}

sub help {
 print STDERR "\n Usage: ps2gif [options] <psfiles>\n\n";
 print STDERR " -pnm/-gif          What format (24/8 bit)               \n";
 print STDERR " -t/-tc <rgb>       Default transparent or: \"0,0.5,1\"  \n";
 print STDERR " -x <x>/-y <y>      Scale picture to x or y size, or both\n";
 print STDERR " -xy <x> <y>        Scale picture within boundary prop.  \n";
 print STDERR " -xdpi <xdpi>       Set only xdpi (96 is default)        \n";
 print STDERR " -ydpi <ydpi>       Set only ydpi (96 is default)        \n";
 print STDERR " -dpi <dpi>         Set both dpi's proportional (96 def.)\n";
 print STDERR " -crop              Crop the picture                     \n";
 print STDERR " -margin <n>        Add <n> pixels margin after crop     \n";
 print STDERR " -colors <col>      Reduce to number of colors           \n";
 print STDERR " -debug             Show debug code while running        \n";
 print STDERR " -quiet             Echo only error messages             \n";
 print STDERR " -help              Show this helptext                   \n";
 print STDERR "\n";
 exit 1;
}
