#!/usr/bin/perl
#
# @package      hubzero-metrics
# @file         xlogplotgraph
# @author       Swaroop Samek <swaroop@purdue.edu>
# @copyright    Copyright (c) 2011-2015 HUBzero Foundation, LLC.
# @license      http://www.gnu.org/licenses/lgpl-3.0.html LGPLv3
#
# Copyright (c) 2011-2015 HUBzero Foundation, LLC.
#
# This file is part of: The HUBzero(R) Platform for Scientific Collaboration
#
# The HUBzero(R) Platform for Scientific Collaboration (HUBzero) is free
# software: you can redistribute it and/or modify it under the terms of
# the GNU Lesser General Public License as published by the Free Software
# Foundation, either version 3 of the License, or (at your option) any
# later version.
#
# HUBzero 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 Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
# HUBzero is a registered trademark of HUBzero Foundation, LLC.
#
# logplotgraph

use strict;

#--- Set system command paths...
#$ENV{'PATH'} = '/opt/gnuplot/bin:/opt/netpbm/bin:/opt/sfw/bin:/bin:/usr/bin:/usr/local/bin';
#$ENV{'LD_LIBRARY_PATH'} = '/opt/gd/lib:/opt/sfw/lib:/opt/usr.local/lib';
my %SYS_PATHS = (
	gnuplot    => 'gnuplot',
	pstopnm    => 'pstopnm',
	jpegtopnm  => 'jpegtopnm',
	ppmtogif   => 'ppmtogif',
	ppmtojpeg  => 'ppmtojpeg',
	ps2pdf     => 'ps2pdf',
	pnmflip    => 'pnmflip',
	pnmcrop    => 'pnmcrop',
	pnmcut     => 'pnmcut',
	pnmmargin  => 'pnmmargin',
	ppmquant   => 'ppmquant',
	rm         => 'rm',
);

#--- Read command-line arguments...
my %args = get_arguments();

#--- Call main gnuplot function...
gnuplot(\%SYS_PATHS, \%args);




#----------------------------------------------------------#
#  gnuplot(\%SYS_PATHS, \%parameters)                      #
#                                                          #
#  %parameters contains:  $output_file, @output_format     #
#                         $title, $y_max, $y_tic, %@plot   #
#  %@plot contains:       $file, $name, $column            #
#----------------------------------------------------------#
sub gnuplot {
	my %SYS_PATHS;
	my %params;
	my $output_file;
	my $output_format;
	my $need_ps;
	my $need_jpg;
	my $keep_ps;
	my $keep_jpg;
	my $keep_ppm;
	my $ppm_exists;
	my $source;

	#--- Get the system paths...
	%SYS_PATHS = %{shift(@_)};

	#--- Get the parameters...
	%params = %{shift(@_)};
	$output_file = $params{'output_file'};

	#--- Set the default gnuplot output (source) format (jpg or ps)...
	$source = "jpg";

	#--- See if any PostScript-dependent formats were requested...
	$need_ps = 0;
	$need_jpg = 0;
	foreach $output_format (@{$params{'output_format'}}) {
	    if($output_format =~ /^PS/i || $output_format =~ /^PDF/i) {
			$need_ps = 1;
		}
		elsif($source eq "jpg") {
			$need_jpg = 1;
		}
	}

	#--- Create Source graph(s)...
	if($need_ps) {
		gnuplot_exec(\%SYS_PATHS, \%params, "ps");
	}
	if($need_jpg) {
		gnuplot_exec(\%SYS_PATHS, \%params, "jpg");
	}

	#--- Track whether any source formats were specifically requested...
	$keep_ps = 0;
	$keep_jpg = 0;

	#--- Several formats are converted from the Portable PixMap (PPM)
	#    format, so we will "cache" it for those formats to save time...
	$ppm_exists = 0;
	$keep_ppm = 0;

	#--- Convert graph to all requested formats...
	foreach $output_format (@{$params{'output_format'}}) {

		#--- Format:  "PostScript (PS)"
		if($output_format =~ /^PS/i) {
			#--- Note the PostScript is to be kept...
			$keep_ps = 1;
		}

		#--- Format:  "JPEG (JPG)"
		elsif($output_format =~ /^JPEG/i || $output_format =~ /^JPG/i) {
			#--- Convert the Source to PPM...
			if(!$ppm_exists) {
				if($source eq "jpg") {
					conv_jpg2ppm(\%SYS_PATHS, \%params, $output_file);
				}
				else {
					conv_ps2ppm(\%SYS_PATHS, \%params, $output_file);
				}

				#--- Cache the PPM format for other converters...
				$ppm_exists = 1;
			}

			#--- Convert PPM to JPG...
			conv_ppm2jpg(\%SYS_PATHS, $output_file);

			#--- Note the JPEG is to be kept...
			$keep_jpg = 1;
		}

		#--- Format:  "Portable Document Format (PDF)"
		elsif($output_format =~ /^PDF/i) {
			#--- Convert the PostScript to PDF...
			conv_ps2pdf(\%SYS_PATHS, $output_file);
		}

		#--- Format:  "Graphic Interchange Format (GIF)"
		elsif($output_format =~ /^GIF/i) {
			#--- Convert the Source to PPM...
			if(!$ppm_exists) {
				if($source eq "jpg") {
					conv_jpg2ppm(\%SYS_PATHS, \%params, $output_file);
				}
				else {
					conv_ps2ppm(\%SYS_PATHS, \%params, $output_file);
				}

				#--- Cache the PPM format for other converters...
				$ppm_exists = 1;
			}

			#--- Convert PPM to GIF...
			conv_ppm2gif(\%SYS_PATHS, $output_file);
		}

		#--- Format:  "Portable Network Graphics (PNG)"
		elsif($output_format =~ /^PNG/i) {
			#--- Convert the Source to PPM...
			if(!$ppm_exists) {
				if($source eq "jpg") {
					conv_jpg2ppm(\%SYS_PATHS, \%params, $output_file);
				}
				else {
					conv_ps2ppm(\%SYS_PATHS, \%params, $output_file);
				}

				#--- Cache the PPM format for other converters...
				$ppm_exists = 1;
			}

			#--- Convert PPM to PNG...
			conv_ppm2png(\%SYS_PATHS, $output_file);
		}

		#--- Format:  "Portable PixMap (PPM)"
		elsif($output_format =~ /^PPM/i) {
			#--- Convert the Source to PPM...
			if(!$ppm_exists) {
				if($source eq "jpg") {
					conv_jpg2ppm(\%SYS_PATHS, \%params, $output_file);
				}
				else {
					conv_ps2ppm(\%SYS_PATHS, \%params, $output_file);
				}

				#--- Cache the PPM format for other converters...
				$ppm_exists = 1;
			}

			#--- Note the PPM "cache" is to be kept...
			$keep_ppm = 1;
		}
		
	}

	#--- If it exists, but was not requested, delete PPM "cache"...
	if($ppm_exists && !$keep_ppm) {
		system("$SYS_PATHS{'rm'} -f $output_file.ppm");
	}

	#--- If not requested, delete original source format(s)...
	if(!$keep_ps) {
		system("$SYS_PATHS{'rm'} -f $output_file.ps");
	}
	if(!$keep_jpg) {
		system("$SYS_PATHS{'rm'} -f $output_file.jpg");
	}

}


#-----------------------------------------------------------------------#
#  gnuplot_exec(\%SYS_PATHS, \%parameters, $source)                     #
#                                                                       #
#  %parameters contains:  $output_file, $title, $y_max, $y_tic, %@plot  #
#  %@plot contains:       $file, $name, $column                         #
#-----------------------------------------------------------------------#
sub gnuplot_exec {
	my %SYS_PATHS;
	my %params;
	my $source;
	my %xrange;
	my $plot;
	my $i;
	my $step;
	my $overlap;
	my $tics;
	my $prevmonth;
	my $month;
	my $year;
	my $tmonth;
	my $tyear;
	my @date;
	my @xdates;
	my $thisdate;
	my $line;
	my $colornum;
	my $output_format;

	#--- Get the system paths...
	%SYS_PATHS = %{shift(@_)};
	
	#--- Get the parameters...
	%params = %{shift(@_)};
	
	#--- Get the JPEG flag...
	$source = shift(@_);
	
	#--- Open gnuplot and interact with it...
	# $ENV{'GDFONTPATH'} = "/usr/openwin/lib/X11/fonts/TrueType";
	$ENV{'GDFONTPATH'} = "/usr/share/fonts/truetype/msttcorefonts";
	open(GNUPLOT, "| $SYS_PATHS{'gnuplot'}") or die "Error:  Cannot connect to gnuplot ($!)\n";
	
	#--- Set the output format and filename...
	if($source eq "jpg") {
		if($params{'thumbnail'}) {
			print GNUPLOT "set terminal jpeg small size 110,44 background '#ffffff'\n";
			print GNUPLOT "set linetype 1 lc rgb '#5884bb'\n";
		}
		else {
			print GNUPLOT "set terminal jpeg small size 320, 250 background '#ffffff'\n";
			print GNUPLOT "set linetype 1 lc rgb '#5884bb'\n";
			# print GNUPLOT "set terminal jpeg small size 640,500 xffffff x000000 x000000 x5884bb font Arial 8\n";
			# print GNUPLOT "set terminal jpeg small size 1280,1000 xffffff x000000 x000000 x5884bb font Arial 8\n";
		}
		print GNUPLOT "set output \"$params{'output_file'}.jpg\"\n";
	}
	else {
		print GNUPLOT "set terminal postscript eps color \"Arial\" 12\n";
		print GNUPLOT "set output \"$params{'output_file'}.ps\"\n";
	}
	
	#--- Set the scales to logarithmic, if desired...
	if($params{'xlog'} ne "") {
		print GNUPLOT "set logscale x;\n";
	}
	if($params{'ylog'} ne "") {
		print GNUPLOT "set logscale y;\n";
	}
	
	#--- Set plot title...
	if($params{'title'}) {
		print GNUPLOT "set title \"$params{'title'}\" font \"Arial,13\"\n";
	}
	
	#--- Set gnuplot options...
#	print GNUPLOT "set key spacing 1.5 left top box\n";
	if($params{'xformat'}) {
		print GNUPLOT "set format x \"" . $params{'xformat'} . "\"\n";
	}
	elsif($params{'xdate'}) {
		print GNUPLOT "set format x \"%b%y\"\n";
	}
	if($params{'xdate'}) {
		print GNUPLOT "set xdata time\n";
		print GNUPLOT "set timefmt \"%m/%Y\"\n";
	}
	elsif(!$params{'xlog'}) {
		print GNUPLOT "set xrange [0:];\n";
	}
	print GNUPLOT "unset mxtics\n";
	print GNUPLOT "unset mytics\n";

	if($params{'thumbnail'}) {
		print GNUPLOT "unset key\n";
		print GNUPLOT "set xtics out nomirror\n";
		print GNUPLOT "set yrange [0:]\n";
		print GNUPLOT "set ytics nomirror\n";
		print GNUPLOT "set format \"\"\n";
	}
	else {
		print GNUPLOT "set xlabel \"$params{'xlabel'}\" font \"Arial,10\"\n";
		print GNUPLOT "set ylabel \"$params{'ylabel'}\" font \"Arial,10\"\n";
		print GNUPLOT "set boxwidth 0.5 relative\n";

	    #--- Set graph axis ranges...
		if($params{'xdate'}) {
		    %xrange = get_xrange(\%params);

		    #--- Make x-axis label
			foreach $plot (@{$params{'plot'}}) {
				open(FILEHANDLE, $plot->{'file'}) or die "Error opening file.\n";
				while(defined($line = <FILEHANDLE>)) {
					if(($month, $year) = $line =~ /^(\d{2})\/(\d{4})\s/) {
						push(@date, $year . sprintf("%02d", $month));
					}
				}
				close(FILEHANDLE);
			}
			@xdates = sort(@date);
			$step = 0;
			$prevmonth = 0;
			foreach $line (@xdates) {
				($year, $month) = $line =~ /^(\d{4})(\d{2})$/;
				if(!$step && $prevmonth) {
				   	if($month > $prevmonth) {
						$step = $month - $prevmonth;
					}
					elsif($month == $prevmonth) {
						$step = 12;
					}
					$overlap = int($step / 2);
				}
				$prevmonth = $month;
			}
			#print GNUPLOT "set label \"April FYTD\" at '03/2005', $y_last\n";
			if(!$step) {
				$step = 1;
			}
		    $tics = int(((monthtoint($xrange{'max'}) - monthtoint($xrange{'min'})) / $step) + 1.5);
			while($tics > 7) {
				if($step == 1) {
					$step = 3;
				}
				elsif($step < 12) {
					$step *= 2;
				}
				else {
					$step += 12;
				}
		    	$tics = int(((monthtoint($xrange{'max'}) - monthtoint($xrange{'min'})) / $step) + 1.5);
			}
			($month, $year) = $xrange{'min'} =~ /^(\d{2})\/(\d{4})$/;

			# Set padding (overlap) on sides of chart data
			if(!$overlap) {
				$overlap = 1;
			}
			($tmonth, $tyear) = $xrange{'min'} =~ /^(\d{2})\/(\d{4})$/;
			$tmonth -= $overlap;
			if($tmonth < 1) {
				$tmonth += 12;
				$tyear--;
			}
			$xrange{'min'} = $tmonth . "/" . $tyear;
			($tmonth, $tyear) = $xrange{'max'} =~ /^(\d{2})\/(\d{4})$/;
			$tmonth += $overlap;
			if($tmonth > 12) {
				$tmonth -= 12;
				$tyear++;
			}
			$xrange{'max'} = $tmonth . "/" . $tyear;

			if($step < 12) {
				while($month % $step) {
					$month++;
				}
			}
			@date = ();
		    while(monthtoint("$month/$year") <= monthtoint($xrange{'max'})) {
				push(@date, sprintf("%02d", $month) . "/" . $year);
				$month = $month + $step;
				while($month > 12) {
				    $month = $month - 12;
				    $year++;
				}
			}
			print GNUPLOT "set xrange [\"$xrange{'min'}\":\"$xrange{'max'}\"]\n";
			print GNUPLOT "set xtics out nomirror (";
			foreach $thisdate (@date) {
				print GNUPLOT "\"$thisdate\"";
				if($thisdate ne $date[$#date]) {
				    print GNUPLOT ", ";
				}
		    }
		    print GNUPLOT ")\n";

		}
	    if($params{'y_max'}) {
			print GNUPLOT "set yrange [0:$params{'y_max'}]\n";
		}
		else {
			print GNUPLOT "set yrange [0:]\n";
		}
		if($params{'y_tic'}) {
		    print GNUPLOT "set ytics 2, $params{'y_tic'}, $params{'y_max'}\n";
	    }
	}

	#--- Issue plot command...
	$i = 1;
	foreach $plot (@{$params{'plot'}}) {
	    if($i == 1) {
			print GNUPLOT "plot ";
	    }
	    else {
			print GNUPLOT ", ";
	    }
	    print GNUPLOT "\"$plot->{'file'}\" using $plot->{'xcolumn'}:$plot->{'column'} title \"$plot->{'name'}\" with ";
	    if($plot->{'type'} eq "bar") {
			print GNUPLOT "boxes fill solid noborder";
	    }
		else {
			print GNUPLOT "line linetype -1 linewidth 1.7";
	    }
		$i++;
	}
	print GNUPLOT "\n";

	#--- Close gnuplot...
	print GNUPLOT "quit\n";
	close(GNUPLOT);
}


#-----------------------------------------------------------------------#
#  get_xrange(\%parameters)                                             #
#                                                                       #
#  %parameters contains:  $output_file, $title, $y_max, $y_tic, %@plot  #
#  %@plot contains:       $file, $name, $column                         #
#-----------------------------------------------------------------------#
sub get_xrange {
	my %params;
	my %xrange;
	my $plot;
	my $line;
	my @fields;
	my $date;
	my $min;

	#--- Get the parameters...
	%params = %{shift(@_)};

	#--- Read plot data file and determine appropriate date range...
	$xrange{'min'} = "";
	$xrange{'max'} = "";
	foreach $plot (@{$params{'plot'}}) {
		if(open(DATFILE, "< $plot->{'file'}")) {
			$date = "";
			$min = "";
			while(defined($line = <DATFILE>)) {
				@fields = split(/\s+/, $line);
				$date = $fields[$plot->{'xcolumn'} - 1];
				if($min eq "") {
					$min = $date;
				}
			}
			if($xrange{'min'} eq "" || monthtoint($min) < monthtoint($xrange{'min'})) {
				$xrange{'min'} = $min;
			}
			if($xrange{'max'} eq "" || monthtoint($date) > monthtoint($xrange{'max'})) {
				$xrange{'max'} = $date;
			}
			close(DATFILE);
		}
		else {
			print STDERR "Error:  Data file \"$plot->{'file'}\" could not be read.\n";
		}
	}

	#--- Return parsed arguments in a hash/structure...
	return(%xrange);
}


#-----------------------------------------------------------------------#
#  monthtoint("mm/yyyy")                                                #
#-----------------------------------------------------------------------#
sub monthtoint {
	my $monthyear;
	my $monthtoint;
	my $month;
	my $year;

	#--- Get the parameters...
	$monthyear = shift(@_);
	($month, $year) = split(/\//, $monthyear);
	$monthtoint = $year * 12 + $month;

	return($monthtoint);
}


sub get_arguments {
	my $arg;
	my %args;
	my %plot;

	#--- Loop through all arguments...
	while($arg = shift(@ARGV)) {

		#--- The output file basename (-o <file_basename>)
		if($arg =~ /^-o(\S*)/) {
			if($1) {
				$args{'output_file'} = $1;
			}
			elsif($ARGV[0] !~ /^-/) {
				$args{'output_file'} = shift(@ARGV);
			}
		}

		#--- Thumbnail option (-thumbnail)
		elsif($arg =~ /^-thumbnail(\S*)/) {
			$args{'thumbnail'} = 1;
		}
		elsif($arg =~ /^-thumb(\S*)/) {
			$args{'thumbnail'} = 1;
		}

		#--- X axis are dates option (-xdate)
		elsif($arg =~ /^-xdate(\S*)/) {
			$args{'xdate'} = 1;
		}

		#--- Logarithmic X Scale (-xlog)
		elsif($arg =~ /^-xlog/) {
			$args{'xlog'} = '1';
		}

		#--- Logarithmic Y Scale (-ylog)
		elsif($arg =~ /^-ylog/) {
			$args{'ylog'} = '1';
		}

		#--- Graph x-label (-xlabel <label>)
		elsif($arg =~ /^-xlabel(\S*)/) {
			if($1) {
				$args{'xlabel'} = $1;
			}
			elsif($ARGV[0] !~ /^-/) {
				$args{'xlabel'} = shift(@ARGV);
			}
		}

		#--- Graph y-label (-ylabel <label>)
		elsif($arg =~ /^-ylabel(\S*)/) {
			if($1) {
				$args{'ylabel'} = $1;
			}
			elsif($ARGV[0] !~ /^-/) {
				$args{'ylabel'} = shift(@ARGV);
			}
		}

		#--- Graph x-format (-xformat <format_string>)
		elsif($arg =~ /^-xformat(\S*)/) {
			if($1) {
				$args{'xformat'} = $1;
			}
			elsif($ARGV[0] !~ /^-/) {
				$args{'xformat'} = shift(@ARGV);
			}
		}

		#--- Graph title (-title <title>)
		elsif($arg =~ /^-title(\S*)/) {
			if($1) {
				$args{'title'} = $1;
			}
			elsif($ARGV[0] !~ /^-/) {
				$args{'title'} = shift(@ARGV);
			}
		}

		#--- The Y max (-ymax <max>)
		elsif($arg =~ /^-ymax(\S*)/) {
			if($1) {
				$args{'y_max'} = $1;
			}
			elsif($ARGV[0] =~ /^\d/) {
				$args{'y_max'} = shift(@ARGV);
			}
		}

		#--- The Y tics (-ytic <tic>)
		elsif($arg =~ /^-ytic(\S*)/) {
			if($1) {
				$args{'y_tic'} = $1;
			}
			elsif($ARGV[0] =~ /^\d/) {
				$args{'y_tic'} = shift(@ARGV);
			}
		}

		#--- The requested output formats (-f <format>...)
		elsif($arg =~ /^-f(\S*)/) {
			if($1) {
				push(@{$args{'output_format'}}, $1);
			}
			while($ARGV[0] !~ /^-/) {
				if($arg = shift(@ARGV)) {
					push(@{$args{'output_format'}}, $arg);
				}
				else {
					last;
				}
			}
		}

		#--- Line or bar plots (-[l|b] <file> <name>...)
		elsif($arg =~ /^-l(\S*)/ || $arg =~ /^-b(\S*)/) {
			if($arg =~ /^-b(\S*)/) {
				$plot{'type'} = "bar";
			}
			else {
				$plot{'type'} = "line";
			}
			if($1) {
				$arg = $1;
				if($arg =~ /^(.*)\{(\d+)\}$/) {
					$plot{'file'} = $1;
					$plot{'xcolumn'} = $2;
				}
				else {
					$plot{'file'} = $arg;
					$plot{'xcolumn'} = 1;
				}
				$plot{'column'} = 2;
				while($ARGV[0] !~ /^-/) {
					if($arg = shift(@ARGV)) {
						if($arg =~ /^(.*)\{(\d+)\}$/) {
							$plot{'name'} = $1;
							$plot{'column'} = $2;
						}
						else {
							$plot{'name'} = $arg;
						}
						push(@{$args{'plot'}}, {%plot});
					}
					else {
						last;
					}
					$plot{'column'}++;
				}
			}
			else {
				while($ARGV[0] !~ /^-/) {
					if($arg = shift(@ARGV)) {
						if($arg =~ /^(.*)\{(\d+)\}$/) {
							$plot{'file'} = $1;
							$plot{'xcolumn'} = $2;
						}
						else {
							$plot{'file'} = $arg;
							$plot{'xcolumn'} = 1;
						}
						$plot{'column'} = 2;
						while($ARGV[0] !~ /^-/) {
							if($arg = shift(@ARGV)) {
								$plot{'name'} . "\n";
								if($arg =~ /^(.*)\{(\d+)\}$/) {
									$plot{'name'} = $1;
									$plot{'column'} = $2;
								}
								else {
									$plot{'name'} = $arg;
								}
								push(@{$args{'plot'}}, {%plot});
							}
							else {
								push(@{$args{'plot'}}, {%plot});
								last;
							}
							$plot{'column'}++;
						}
					}
					else {
						last;
					}
				}
			}
		}

		#--- Print usage and return an error if any
		#    options could not be properly interpreted...
		elsif($arg =~ /^-/) {
			exit(&print_usage("Invalid option `$arg'"));
		}
		elsif($arg =~ /^\S+/) {
			exit(&print_usage("Invalid flag `$arg'"));
		}

	}

	#--- Check for required arguments...
	if($args{'output_file'} eq "") {
		exit(print_usage("No output file basename specified."));
	}

	#--- Return parsed arguments in a hash/structure...
	return(%args);
}


sub print_usage {
	my $error;

	$error = shift(@_);

	print STDERR "\n";
	if($error) {
		print STDERR "Invalid usage:  $error.\n";
		print STDERR "\n";
	}
	print STDERR "Usage:  logplotgraph -o <output_basename>\n";
	print STDERR "        -f <output_format> [<output_format> ...]\n";
	print STDERR "        [-ymax <y_max>] [-ytic <y_ticsize>]\n";
	print STDERR "        [-ylabel <y_label>] [-xformat <x_format>]\n";
	print STDERR "        -p <plot_file>[{<x_col>}] [<plot_name>[{<y_col>}]]\n";
	print STDERR "\n";

	return(1);
}


sub conv_ps2ppm {
	my %SYS_PATHS;
	my $output_file;
	my %params;
	my $size;

	#--- Get the system paths...
	%SYS_PATHS = %{shift(@_)};

	#--- Get parameters...
	%params = %{shift(@_)};

	#--- Get the output filename...
	$output_file = shift(@_);

	#--- Set output graph size...
	if($params{'thumbnail'}) {
	    $size = " -xsize 20 -ysize 80";
	}
	else {
		$size = " -xsize 231 -ysize 320";
	}

	#--- Convert the file...
	system("$SYS_PATHS{'pstopnm'} -stdout${size} -ppm ${output_file}.ps > ${output_file}_tmp.ppm 2> /dev/null");
	if($params{'thumbnail'}) {
		system("$SYS_PATHS{'pnmflip'} -rotate270 ${output_file}_tmp.ppm | $SYS_PATHS{'pnmcrop'} > $output_file.ppm 2> /dev/null");
	}
	else {
		system("$SYS_PATHS{'pnmflip'} -rotate270 ${output_file}_tmp.ppm | $SYS_PATHS{'pnmcrop'} | $SYS_PATHS{'pnmmargin'} -white 8 > $output_file.ppm 2> /dev/null");
	}
	system("$SYS_PATHS{'rm'} -f ${output_file}_tmp.ppm");
}


sub conv_jpg2ppm {
	my %SYS_PATHS;
	my $output_file;
	my %params;

	#--- Get the system paths...
	%SYS_PATHS = %{shift(@_)};

	#--- Get parameters...
	%params = %{shift(@_)};

	#--- Get the output filename...
	$output_file = shift(@_);

	#--- Convert the file...
	system("$SYS_PATHS{'jpegtopnm'} -dct float ${output_file}.jpg > ${output_file}_tmp.ppm 2> /dev/null");
	if($params{'thumbnail'}) {
		system("$SYS_PATHS{'pnmcut'} -left 18 -top 11 -width 74 -height 20 ${output_file}_tmp.ppm > $output_file.ppm 2> /dev/null");
	}
	else {
		system("$SYS_PATHS{'pnmcrop'} ${output_file}_tmp.ppm | $SYS_PATHS{'pnmmargin'} -white 4 > $output_file.ppm 2> /dev/null");
	}
	system("$SYS_PATHS{'rm'} -f ${output_file}_tmp.ppm");
}


sub conv_ppm2gif {
	my %SYS_PATHS;
	my $output_file;

	#--- Get the system paths...
	%SYS_PATHS = %{shift(@_)};

	#--- Get the output filename...
	$output_file = shift(@_);

	#--- Convert the file...
	system("$SYS_PATHS{'ppmquant'} 256 ${output_file}.ppm > ${output_file}_tmp.ppm 2> /dev/null");
	system("$SYS_PATHS{'ppmtogif'} ${output_file}_tmp.ppm > ${output_file}.gif 2> /dev/null");
	system("$SYS_PATHS{'rm'} -f ${output_file}_tmp.ppm");
}


sub conv_ppm2jpg {
	my %SYS_PATHS;
	my $output_file;

	#--- Get the system paths...
	%SYS_PATHS = %{shift(@_)};

	#--- Get the output filename...
	$output_file = shift(@_);

	#--- Convert the file...
	system("$SYS_PATHS{'ppmtojpeg'} $output_file.ppm > $output_file.jpg 2> /dev/null");
}


sub conv_ps2pdf {
	my %SYS_PATHS;
	my $output_file;

	#--- Get the system paths...
	%SYS_PATHS = %{shift(@_)};

	#--- Get the output filename...
	$output_file = shift(@_);

	#--- Convert the file...
	system("$SYS_PATHS{'ps2pdf'} $output_file.ps");
}


sub conv_ppm2png {
	my %SYS_PATHS;
	my $output_file;

	#--- Get the system paths...
	%SYS_PATHS = %{shift(@_)};

	#--- Get the output filename...
	$output_file = shift(@_);

	#--- Convert the file...
	print STDERR "Convert PPM to PNG not yet implemented...\n";
}








