#!/usr/bin/perl -w


###########################################################################
#
# pstoimg.pl -- convert PS documents to various types of Image format
#
# A component of the Greenstone digital library software
# from the New Zealand Digital Library Project at the 
# University of Waikato, New Zealand.
#
# Copyright (C) 2001 New Zealand Digital Library Project
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
# 
###########################################################################
# pstoimg.pl is a wrapper for running convert utility which converts
# PS documents to various types of image (e.g. PNG, GIF, JPEG format, 
# Then use PagedImgPlug to deal with the the images
# Chi-Yu Huang 08.2005

BEGIN {
    die "GSDLHOME not set\n" unless defined $ENV{'GSDLHOME'};
    unshift (@INC, "$ENV{'GSDLHOME'}/perllib");
}

use parsargv;
use util;
use Cwd;
use File::Basename
;
sub print_usage {
    # note - we don't actually ever use most of these options...
    print STDERR  
	("pstoimg.pl wrapper for pstoimg.\n",
	 "Usage: pstoimg [options] <PS-file> <output>\n",
	 "Options:\n",
	 "\t-convert_to\toutput image type for the PS\n"
	 );
    exit (1);
}

sub main {
    my (@ARGV) = @_;
    my ($convert_to);
     
    # read command-line arguments so that
    # you can change the command in this script
    if (!parsargv::parse(\@ARGV,
			 'convert_to/.*/^', \$convert_to,
			 )) {
    	print_usage();
    }
 
    # Make sure the input file exists and can be opened for reading
    if (scalar(@ARGV) != 2) {
	print_usage();
    }

    my $input_filename = $ARGV[0];
    my $output_filestem = $ARGV[1];
    
    # test that the directories exist to create the output file, or
    # we should exit immediately. (File:: is included by util.pm)
    &util::mk_dir($output_filestem) if (!-e $output_filestem);
	    
    my @dir = split (/(\/|\\)/, $input_filename);
    my $input_basename = pop(@dir);
    $input_basename =~ s/\.ps//i;
    my $dir = join ("", @dir);
    
    if (!-r $input_filename) {
	print STDERR "Error: unable to open $input_filename for reading\n";
	exit(1);
    }
    # don't include path on windows (to avoid having to play about
    # with quoting when GSDLHOME might contain spaces) but assume
    # that the PATH is set up correctly.
    $cmd = "convert";
    #if ($ENV{'GSDLOS'} =~ /^windows$/);
    #Convert utility will convert the PS to GIF Animation
    my $output_filename = &util::filename_cat($output_filestem, $input_basename);
    if ($convert_to eq "gif") {
	$cmd .= " \"$input_filename\" \"$output_filename-%02d.$convert_to\"";
    } else {
	$cmd .= " \"$input_filename\" \"$output_filename.$convert_to\"";
    }	

    # system() returns -1 if it can't run, otherwise it's $cmds ret val.
    # note we return 0 if the file is "encrypted"
    $!=0;
    if (system($cmd)!=0) {
	print STDERR "Convert error for $input_filename $!\n";
	# leave these for gsConvert.pl...
	#&util::rm("$output_filestem.text") if (-e "$output_filestem.text");
	#&util::rm("$output_filestem.err") if (-e "$output_filestem.err");
	return 1;
    } else {
	# command execute successfully
	create_itemfile($output_filestem, $input_basename, $convert_to);
    }
    return 0;
}

sub create_itemfile
{
    my ($output_dir, $convert_basename, $convert_to) = @_;
    opendir(DIR, $output_dir) || die "can't opendir $output_dir: $!";  
    my $item_file = $output_dir."/".$convert_basename.".item";
    open(FILE,">$item_file");
    
    print FILE "<PagedDocument>\n";

    my $page_num = "";
    @dir_files = grep {-f "$output_dir/$_"} readdir(DIR);

    # Sort files in the directory by page_num    
    sub page_num {
	my ($dir) = @_;
	my $pagenum = "";
	if ($ENV{'GSDLOS'} =~ /^windows$/){
	   ($pagenum) =($dir =~ m/^.*\.(\d+)$/i);   
	} else {
	   ($pagenum) =($dir =~ m/^.*-(\d+)\.(.*)$/i);
	}
	$pagenum = $pagenum || 1;
	return $pagenum;
    }

    # sort the files in the directory in the order of page_num rather than lexically. 
    @dir_files = sort { page_num($a) <=> page_num($b) } @dir_files;

    foreach my $file (@dir_files){
        if ($ENV{'GSDLOS'} =~ /^windows$/ && $convert_to ne "gif"){
	  ($page_num) =($file =~ m/^.*\.(\d+)$/i); 
	} else {
	    ($page_num) =($file =~ m/^.*-(\d+)\.(.*)/i);   
	}
	# as the converter will convert the document to image files start from page 0
	$page_num =$page_num + 1 if defined $page_num;
	$page_num = 1 unless defined $page_num;
	if ($file !~ /\.item/i){
	    print FILE "   <Page pagenum=\"$page_num\" imgfile=\"$file\" txtfile=\"\"/>\n";
	} 
    }

    print FILE "</PagedDocument>\n";
    closedir DIR;
    return "";
}

# indicate our error status, 0 = success
exit (&main(@ARGV));



