#!/usr/local/bin/perl
#$XConsortium: psconvert /main/1 1996/09/24 12:41:06 ray $
##############################################################################
# psconvert.pl -- Wrapper around third-party conversion utility to convert
#                 from PostScript to another graphics format (such as GIF).  
#
#
# USAGE:       psconvert <style> <input> <out> <w> <h> <format> <add_args>
#
#              <style>        Either '-in' or '-ex' depending on whether the
#                             image is to be an inline image or external image.
#
#              <in>           Name of the incoming PostScript file.
#
#              <out>          Name of the file after it has been converted.  The
#                             extension on the file is as specified to the 
#                             MifMucker.  So determine format from that.
#
#              <w>            Width of the image (in inches)
#
#              <h>            Height of the image (in inches)
#
#              <format>       Graphics format of final image.
#
#              <add_args>     Additional arguments from MifMucker command line
#
# DESCRIPTION: converts PostScript files containing a single 
#              graphic into another format for use with the 
#              World Wide Web (HTML).  This script is used in 
#              conjunction with the MifMucker and should not be 
#              called directly, except for special circumstances.
#
#              The script is passed 6 arguments.  The name of the file 
#              containing the PostScript ($in), the name of the output
#              file that should be CREATED by this script ($out), the
#              width and height of the image in inches ($W and $H), the
#              graphic format the destination image should be in ($format)
#              and whether the image is going to be an external or inlined
#              image ($style).  If it is inline, $style is "-in", and if
#              it is external, $style is "-ex".
#
#              The image appears in the top left corner of the PostScript
#              page.  Hence, you will most likely want to clip the image
#              so that you don't get all the extra white space.  That's why
#              you are passed the width and height of the image.
#
# WARNING:     DO NOT UNLINK OR RENAME THE FILE PASSED IN AS $in!!
#              DO UNLINK ALL FILES YOU CREATE (EXCEPT OF COURSE $out)!!
#
##############################################################################

$DEBUG = 1 ;
&main(@ARGV); # I just like it this way :-)

sub main {
    local($style, $in, $out, $W, $H, $format, $add_args) = @_ ; 
    local($DPI)   = 300 ;
    local($SCALE) = "25%x25%" ;
    local($MIFF)  = "miff.miff" ; # MIFF graphics format (unrelated to MIF!)
    local($GIF)   = "gif.gif" ;   # GIF graphics format (color)
    local($dim)   = "" ;
    local($dpi)   = "" ;
    local($scale) = "" ;

    print "\n       --- psconvert ---\n" ;
    print " Input file is  : $in\n" if ($DEBUG);
    print " Output file is : $out\n" if ($DEBUG);
    print " Width  is      : $W\n" if ($DEBUG);
    print " Height is      : $H\n" if ($DEBUG);
    print " Style is       : $style\n"  if ($DEBUG);
    print " Format is      : $format\n"  if ($DEBUG);
    print " Additional Args: $add_args\n"  if ($DEBUG);
   
    #-----------------------------------------------------------------
    # This next bit of code demonstrates how to enable the user to 
    # further control the behavior of this script through the $add_args
    # argument.  In this case, the $add_args specifies the DPI and
    # optionally the scale factor for inline images.
    #
    # Because the add_args is a single string, we seperate these two
    # values with two colons.  So, the user would invoke the MifMucker
    # and specify the additional arguments to psconvert like so:
    #
    # % mifmucker html my.doc -Phtml "-ps_args 300::25%25%"
    #
    # And this script would take the first number as a DPI and the second
    # as the scale factor.  If either of this is missing, the defaults
    # above are used (always remember to specify defaults!).
    #-----------------------------------------------------------------

    if ($add_args) {
        ($dpi, $scale) = split('::', $add_args);
        $DPI   = $dpi   if $dpi   ;
        $SCALE = $scale if $scale ;
    }


    if ($format =~ /ps/i) {
        &copy($in, $out);
    }
    elsif ($format =~ /gif/i) {
        #-----------------------------------------
        # The following code depends upon the ImageMagick tools
        # being available on your machine, and having a version
        # of Ghostscript that can convert PostScript for
        # the ImageMagick tools.
        #
        # To determine if your version of GhostScript links in the
        # the appropriate libraries, use gs -h and look for:
        #
        # Available devices:
        #     x11 pbm pbmraw pgm pgmraw ppm ppmraw bit
        #
        # I think only the pbm, pbmraw, pgm, and pgmraw are necessary.
        #-----------------------------------------

        $W      = ($W*$DPI) + 1 ;
        $H      = ($H*$DPI) + 1 ;
        $dim    =  int($W) . "x" . int($H) ;

        print "Clipping to $dim, at $DPI DPI, saving as MIFF..." if ($DEBUG);
        if (system("convert -density ${DPI}x${DPI} -clip $dim $in $MIFF")!=0){
            print "failed!\n" ;
        }
        else {
            print "succeeded!\n" ;
        }

        if ($style eq "-in") {
            print "Inlined; scaling to $SCALE, saving as $MIFF..." if ($DEBUG);
            if (system("mogrify -geometry $SCALE $MIFF") != 0) {
                print "failed!\n" ;
            }
            else {
                print "succeeded!\n" ;
            }
        }

        if (-e $MIFF) {
            print "Converting $MIFF to $GIF..." if ($DEBUG);
            if (system("convert $MIFF $GIF") != 0) {
                print "failed!\n";
            }
            else {
                print "succeeded!\n";
            }
        }

        if (-e $GIF) {
            print "Moving $GIF to $out\n" if ($DEBUG);
            &copy($GIF, $out);
        }

        #------------------------------------------
        # We don't unlink $out nor $in!!!
        #------------------------------------------
        unlink($MIFF) if (-e $MIFF);
        unlink($GIF)  if (-e $GIF);
    }
    else {
        print STDOUT "Unrecognized format: $format ...doing nothing!\n" ;
    }
    print "\n       --- psconvert ---\n" ;
}




sub copy {
    local($src, $dest) = @_ ;

    open (SRC, "$src") || die "Unable to open $src : $!\n" ;
    open (DES, ">$dest") || die "Unable to open $dest : $!\n" ;
    while (<SRC>) {
       print DES ;
    }
    close DES || die "Unable to close $src : $!\n" ;
    close SRC || die "Unable to close $dest : $!\n" ;
}
