#!/usr/bin/perl
#
# $Id: image_jpeg.pl,v 1.4 2000/01/26 23:52:29 tim Exp $#
#
# Return a decompressed MrSID image.

require "cgi-lib.pl";
require "config.pl";

$| = 1;

$rc = &ReadParse;
if (!$rc) {
   # No form input.
   print "Improper request, no form data.";
   exit (0);
}

$x      = $in{x};
$y      = $in{y};
$level  = $in{level};
$width  = $in{width};
$height = $in{height};

$client = $in{client};
$image  = $in{image};

# Check for watermark variable
if($watermark) {
	$img_name = $image;	
	$img_name =~ s/\.[sS][iI][dD]//g;
	
	$query_wm = "$mrsid_server/$client/$img_name".".info";
	# print "$query_wm\n\n";
	
	$rc = open (TEMP, "$query_wm");
	if ($rc != 0) {
		while (<TEMP>) {
		   if ($_ =~ m/WMFILE:/) {
			   $_ =~ s/WMFILE://g;
				$wmfile = $_;
				chomp $wmfile;	
			} elsif ($_ =~ m/WMPOS:/) {
				$_ =~ s/WMPOS://g;
				$wmpos = $_;
			}
		}
		close (TEMP);
			
		if ($wmfile eq "") {
			$wmparams = "";
		} elsif ($wmpos eq "") {
			$wmparams = "-wm $image_path/$client/$wmfile";
		} else {
			$wmparams = "-wm $image_path/$client/$wmfile -wp $wmpos";
		}				
		
	} else {
		# namefile not opened, can't find watermark name
		$wmparams = "";
	}
} else {
	# Configured to disallow watermarks
	$wmparams = "";
}

$img  = "$image_path/$client/$image";
$prog   = "$mrsid_bin/mrsid_retrieve -quiet -i";

$cmd = "$prog $img -x $x -y $y -s $level -w $width -h $height -o $tempfile $wmparams 1>/dev/null 2>&1";
# print "$cmd\n";

$rc = system ($cmd);
if ($rc != 0) {
  unlink ($tempfile);
  print "Failed to extract information, check file space, executables.\n\n";
  print "$cmd\n";
  exit (0);
}

$rc = open (IMAGE, $tempfile);
if (!$rc) {
  # Failed to open temp jpeg file --> Error out, quit.
  print "Failed to open temp file.\n";
  print "$cmd\n";
  unlink ($tempfile);
  exit (0);
}

print "Content-Type: image/jpeg\n\n";

print <IMAGE>;
close (IMAGE);
unlink ($tempfile);

exit (0);
#########################################################
# End of Program
#########################################################
