#!/usr/bin/perl -w
############################################################################
#		**** Varriable Settings ****
############################################################################
#Please configure for your system.
############################################################################
#Tells the program where your main page is (we use this to determine the 
#file structure).
$web_base = "http://hep.uchicago.edu/~drschuet/public_html";

#Tells the program where to drop the converted file; this location should
#be relative to the location of the main web page.
$dir_base = "/home/hep/drschuet/public_html";
$dir_docs = "database/docs";
$dir_figs = "database/figures";
$dir_work = "database/working";

#The URL of the directory where this cgi is stored.
$cgi_url = "http://hep.uchicago.edu/cgi-bin"; 

############################################################################
#               **** Specks and Neccessities ****
############################################################################
$ENV{'PATH'} = "/usr/local/bin:/usr/bin:/bin:/usr/local/bin/teTeX/bin";
use File::Copy "cp" || print "Can't use copy.";
############################################################################
#Initial response to server.
print "Content-type: text/html\n\n";
print "<HTML>\n";
print "<HEAD>\n";

#Get info on the conversion from the enviroment defined for the program by 
#the server.
($conversion_info = $ENV{'QUERY_STRING'}) or &err_noinfo ;

#Process the info on the conversion into something we can work with.
foreach $bitowork (split (m/\&/, $conversion_info)) {
#	print "$bitowork\n";
	$bitoname = '';
	$bitovalue = '';
	($bitoname, $bitovalue) = (split( m/=/, $bitowork));

	#Run a subroutine to decode the URL encoding.
	$bitovalue = url_decoding($bitovalue);
	$bitoname = url_decoding($bitoname);

	#There are three characteristics attached to each converable 
	#file. Its old file type, its new file type and the location of its
	#Source. First check to see if we are dealing with the new or the 
        #old file types. If we are looking at new we want to bundle its
	#value into a hash for future refference. If we are looking at
	#old we just need to make sure that the value is indexed as
	#the varriable name. Finnaly if we have a location, just save it
	#as a varriable and deal with it later.
	if ("$bitoname" =~ /^new_/ ) {
		$bundle{$bitoname} = "$bitovalue";
	} 
	elsif ("$bitoname" =~ /(^old_|^loc_|^query_name$)/ ) {
		$bagu = "$bitoname";
		$$bagu = "$bitovalue";
	}
	else {
		print "This is not as it should be.\n";
	}
}

#We begin our response now.
$rslts_a .= "<TITLE>Conversion Results</TITLE>\n";
$rslts_a .= "<BASE HREF=\"$web_base\">\n";
$rslts_a .= "</HEAD>\n\n";
$rslts_a .= "<BODY BACKGROUND=\"backgrounds/bg1944.jpg\">\n";
$rslts_a .= "<H3 ALIGN=center><HR>\n";
$rslts_a .= "<FONT COLOR=blue>Results for query \`\`$query_name\'\'</FONT>\n";
$rslts_a .= "<HR></H3>\n\n";

$rslts_b .= "<FORM ACTION=\"$cgi_url/mh_gamma\" METHOD=\"GET\">\n\n";
$rslts_b .= "<INPUT TYPE=\"hidden\" NAME=\"query_name\" VALUE=\"$query_name\">\n";
$rslts_b .= "<CENTER>\n<TABLE BORDER>\n";

#Now we go through the hash to see if any conversions have been requested.
foreach $n_filename (sort keys %bundle) {

        #There are a lot of places in this part of gamma where I convert
        #the names of keys to the hash so that I can use the converted 
        #names to access the values of other varriables.
        $o_filename = new_to_old($n_filename);
	$l_filename = new_to_loc($n_filename);
	$filename_ext = rm_pre($n_filename);
	$filename_noext = rm_ext($filename_ext);
############################################################################
#                       Formating and Setting Varriables
#			Under Heavy Construction
############################################################################
	#If there are no charges skip to the next value.  
	if ($bundle{$n_filename} eq "$$o_filename") {
		$filename = $filename_ext;		
		($bundle{$n_filename} eq "LaTeX Source") ? ($f_ref = "$$l_filename") : ($f_ref = "$dir_work/$filename");
	} 
	else {
		if ($bundle{$n_filename} eq "LaTeX Source") {
			(-e "$dir_base/$$l_filename") ? ($filename = "$filename_noext\.tex") : (err_gen("the LaTeX source appears to be missing")); 
			$f_ref = "$$l_filename";
		}
		elsif ($bundle{$n_filename} eq "LaTeX \.dvi") {
		        (-e "$dir_base/$dir_work/$filename_noext\.dvi") ? ($filename = "$filename_noext.dvi") : ($filename = tex_to_dvi($filename_ext));
			$f_ref = "$dir_work/$filename";
		}
		elsif ($bundle{$n_filename} eq "Post Script") {
		        (-e "$dir_base/$dir_work/$filename_noext.dvi") ? ($dvi_filename = "$filename_noext.dvi") : ($dvi_filename = tex_to_dvi($filename_ext));
			(-e "$dir_base/$dir_work/$filename_noext.ps") ? ($filename = "$filename_noext.dvi") : ($filename = dvi_to_ps($dvi_filename));
			$f_ref = "$dir_work/$filename";
		}
		else {
		        print STDERR "Something is wrong with $l_filename.\n";
		}
	}
############################################################################
#                      Preparing the Response Line
############################################################################
	$rslts_b .= "\n<TR>\n";
	$rslts_b .= "<TD><A HREF=\"$f_ref\">$filename</A></TD>\n";
	$rslts_b .= "<TD>\n";
	$rslts_b .= "   <INPUT TYPE=\"hidden\" NAME=\"loc_$filename\" VALUE=\"$$l_filename\">\n";
	$rslts_b .= "   <INPUT TYPE=\"hidden\" NAME=\"old_$filename\" VALUE=\"$bundle{$n_filename}\">\n";

	#Determine default format.
	$rslts_b .= "   <SELECT NAME=\"new_$filename\">\n";
	($bundle{$n_filename} eq "LaTeX Source") ? ($rslts_b .= "      <OPTION SELECTED>LaTeX Source</OPTION>\n") : ($rslts_b .= "      <OPTION>LaTeX Source</OPTION>\n");
        ($bundle{$n_filename} eq "LaTeX \.dvi") ? ($rslts_b .= "      <OPTION SELECTED>LaTeX \.dvi</OPTION>\n") : ($rslts_b .= "      <OPTION>LaTeX \.dvi</OPTION>\n");
	($bundle{$n_filename} eq "Post Script") ? ($rslts_b .= "      <OPTION SELECTED>Post Script</OPTION>\n") : ($rslts_b .= "      <OPTION>Post Script</OPTION>\n");
	$rslts_b .= "   </SELECT>\n";
	$rslts_b .= "</TD>\n";
	$rslts_b .= "<TD>\n";
	$rslts_b .= "<INPUT TYPE=\"submit\">\n";
	$rslts_b .= "</TD>\n";
	$rslts_b .= "<TD>\n";
	$rslts_b .= "<INPUT TYPE=\"reset\">\n";
	$rslts_b .= "</TD>\n";
	$rslts_b .= "</TR>\n";
}

#Attach an end note.
$rslts_b .=  "\n</TABLE>\n</CENTER>\n</FORM>\n</BODY>\n</HTML>\n";

#Publish a.
print "$rslts_a";

#Publish b.
print "$rslts_b";

############################################################################
#                      <--> Subroutines <-->
############################################################################
sub err_gen {
        local($comment) = @_;
        print STDERR "Comment: $comment\n";
        print "<TITLE>Gereral Error</TITLE>\n";
	print "<BASE HREF=\"$web_base\">";
	print "</HEAD>\n\n";
	print "<BODY BACKGROUND=\"backgrounds/bg1811.jpg\">\n\n";
	print "<HR>\n";
	print "<H3 ALIGN=center>\n<FONT COLOR=red>\n";
	print "General Error\n";
	print "</FONT>\n</H3>\n<HR>\n\n";
	print "<P>Some sort of catestrophic event has occured and the whole thing just blew up. ";
	print "Please advide the person respondsible for this mess that he should start picking up the pieces.</P>\n\n";
	print "<HR>\n<H3 ALIGN=center>\n<FONT COLOR=blue>Have a nice day!</FONT>\n</H3>\n\n";
	print "</BODY>\n\n</HTML>";
	exit -1;
}

############################################################################
sub err_noinfo {
        print "<TITLE>No Info</TITLE>\n";
	print "</HEAD>\n\n";
	print "<BODY>\n";
	print "<H3 ALIGN=center>No Info</H3>\n";
	print "<P>An error has occured because the scrip was called without any arguements.</P>\n\n";
	print "</BODY>\n\n</HTML>";
	exit -1;
}
############################################################################
#Converts LaTeX Source Files to .dvi.
sub tex_to_dvi {
	local($filename) = @_;
	chomp($filename);
	
	cp("$dir_base/$dir_docs/$filename", "$dir_base/$dir_work");
	$image_file = imgs($filename);
	if (-e "$dir_base/$dir_figs/$image_file") {
	    open(IMAGES, "$dir_base/$dir_figs/$image_file") or print STDERR "Can't open $image_file.\n";
	    while (defined($image = <IMAGES>)) {
		chomp($image);
		cp("$dir_base/$dir_figs/$image", "$dir_base/$dir_work");
	    }
	    close(IMAGES)
	}
	else { 
	    print STDERR "No images processed";
	}
	chdir "$dir_base/$dir_work" or err_gen("trouble changing to working directory.");
	$cmd = "latex $filename";
	`$cmd` or err_gen("could not successfully execute LaTeX command line.");
	$_ = $filename;
	s/.tex$/.dvi/;
        (-e "$dir_base/$dir_work/$_") ? (return $_) : (err_gen('.dvi was not created.'));
}

############################################################################
#Converts a .dvi file to Post Script.
sub dvi_to_ps {
	my($dvi_filename) = @_;
	chdir "$dir_base/$dir_work";
	`dvips $dvi_filename`;
	$_ = $dvi_filename;
	s/.dvi$/.ps/;
	(-e "$dir_base/$dir_work/$_") ? (return $_) : (err_gen('.ps was not created'));
}

############################################################################
sub imgs {
	local($_) = @_;
	s/(.tex$)/.images/;
	return $_;
}

############################################################################
sub rm_pre {
	local($_) = @_;
	s/^new_|^old_|^loc//;
	return $_;
}

############################################################################
sub rm_ext {
	local($_) = @_;
	s/\.(...)//;
	return $_;
}

############################################################################
sub new_to_old {
	local($_) = @_;
	s/^new_/old_/;
	return $_;
}

############################################################################
sub new_to_loc {
	local($_) = @_;
	s/^new_/loc_/;
	return $_;
}

############################################################################
sub url_decoding {
	#This bit of decoding is borrowed from a contribution to 
	#Webglimpse which I believe as writen by Peter Bigot, although
	#the actual code appears to have been added by someone else.
	local($_) = @_;
	s/\+/ /g;
	s/%([A-Fa-f0-9]{2})/pack("c",hex($1))/ge;
	return $_;
}

		










