#!/usr/bin/env perl

## $Id$

####################################################################
# Copyright @ 1995-1998 University of Rochester
# All Rights Reserved
####################################################################

use strict;

use lib '.'; use webworkInit; # WeBWorKInitLine
# this is the home directory. (change to system)
use Global;
use Pod::Html;
use Carp;
use CGI qw(:standard);
#eval {
$| = 1;		#force command buffering
print "Content-type: text/html\n\n";
$| = 0;
# augment the paths to search for documentation.
# e.g. '/webwork/experimental/courseScripts', '/webwork/experimental/scripts', 
# This is not fool proof, but it will work if the webwork system has been set up as at U. of Rochester.


#my $dir3 = "/ww/webwork/development/";  #kludge for the summer so that the latest docs make it to the web.
my $dir3 = $Global::mainDirectory;
unshift(@INC,$dir3);
unshift(@INC, $dir3.'courseScripts/',$dir3.'scripts/',$dir3.'cgi/cgi-scripts/');
my $dir4 = "/u/gage/webwork-modperl/lib/";
unshift( @INC, $dir4.'Apache/', $dir4.'WeBWorK/', $dir4.'WeBWorK/PG/',  $dir4.'WeBWorK/ContentGenerator/'                );
  
#   End defining search paths.

open( LOG, ">pod2webwork.log" ) or warn "Can't open pod2webwork.log for writing";
#print LOG "";
#close( LOG );
#open( LOG, ">>pod2webwork.log" );

my $path = param('path');

my $HTMLpre = 0;		#for use with clipline(); must be global to this file
						#because it's used over multiple calls of clipline()
 
my $up_path = referer(); #This is the URL that the "up" button will point to.
if (defined $up_path)  {
	# point to the index of the directory
	$up_path =~ s|/[^/]*$|/index.html|g;
	
} else {
	$up_path = "${Global::webworkDocsURL}";
}


# Now find the path to the file
my $p;

foreach $p ("",@INC) {
	if (-r "$p$path") {
		$path = "$p$path";
		#print "found $path<BR>\n";
		last;
	}
	#print "looking for $p$path<BR>\n";
}

output_filter();   # install output filter


pod2html($path, "--title= ");  # produces a blank title, eliminating error message.
                               # real title is produced in output_filter
close(STDOUT);
close( LOG );



#}; # end eval

print "Content-type: text/html\n\n <PRE> $@ </PRE>" if $@;

###########

   # This will print to STDOUT which will then be filtered.
sub output_filter{
      # use command buffering;
    my $pid;
    
    return if $pid = open(STDOUT, "|-") ;  #I'm not sure why this works -- see Perl cookbook.
    
	print <<EOT;

	<html>
	<head>
	<title>$path</title>
	</head>
	<body alink="#008000" bgcolor="#FFFFFF" link="#0000FF" vlink="#800080"><p>

	 <!--ALIGN = "CENTER" -->
	<IMG SRC="${Global::imagesURL}webwork-short.gif"  BORDER=1 ALT ="WeBWorK" ALIGN = "LEFT"  >
	<P ALIGN=RIGHT>
	         <A HREF="$up_path"  ><IMG SRC="$Global::upImgURL"   BORDER=1 ALT ="[Up]"  ></A>       
	         <A HREF="/cgi-bin/feedback"><IMG SRC="$Global::feedbackGifUrl"   BORDER=1 ALT ="[Feedback]"  ></A>
	<BR CLEAR=ALL><HR NOSHADE><p>

	<BLOCKQUOTE>
EOT
    
 	unless (-r $path) {
 		print "<H3> Missing documentation</H3>";
 		print "Can't find file <CODE>$path</CODE> after searching in the following directories:<BR>";
 		print join("<BR>",@INC);
 	}
 	
     unless ( defined($pid) ) {
     	print "<H3> Can't find the file $path </H3>";
     	return;
     }

# get rid of the html header
	while (<STDIN>)  {
		last if /<BODY>/;
	}
	
	while (<STDIN>) {
		my $line = $_;
		last if $line =~ m{</BODY>}i;
		chomp($line);
		print clipline($line);
	}

	print <<EOT;
	 <p><H6>File path = $path</H6>
	</BLOCKQUOTE>
	<HR NOSHADE>
	Last updated: <STRONG>12 August 1999</STRONG>&nbsp;
	<TT>$path</TT>
	<BR><FONT SIZE="-2"><STRONG><EM>WeBWorK</EM> documentation written by M. Gage, E. Pachepsky and A. Pizer.  
	<BR>This page was built by <A HREF = "mailto:gage\@math.rochester.edu">M.Gage</A> 
	</STRONG></FONT>
	</body>
	</html>
EOT

exit;
} # end output filter

# Routine authors: Arnold Pizer and Michael Gage
# modified by David Etlinger
#
# This routine handles indenting the line and wrapping it, and other formatting
# issues. The incoming text includes HTML tags; code which wraps lines at a
# certain number of characters must ignore these tags. The assumptions I'm making
# about the incoming text are:
#	1)	It contains HTML tags already
#	2)	Special characters (like &) are replaced by HTML codes (like &amp;)
#	3)	Most tabs have already been replaced by spaces (this is a pain to deal with!)
#			Pod2HTML uses 8-column tabs, while we want to use 4-column. Also, 2 or
#			more consecutive spaces are assumed to be a tab. So incoming 8-column
#			tabs need to be converted to 4-column tabs.
# Some of these assumptions might not be valid if pod2HTML changes, or other
# system components are modified.
#											--David Etlinger 7/27/2000
sub clipline {
	my $inLine = shift @_;
	
	#DEBUG
	# $inLine =~s/&quot([^;])/&quot;$1/g;  # work around for bad quoting in pod2html for links
	print LOG "${inLine}\n";
	
	$inLine = '' unless $inLine =~ /\S/;		#treat lines with only whitespace as blank
	$HTMLpre = 1 if $inLine =~ m|<PRE>|i;		#$HTMLpre assumes <PRE> begins the line
	
	$inLine =~ s/``/&quot;/g;		#use &quot; for increased browser compatibility
	$inLine =~ s/''/&quot;/g;
	# $inLine =~ s/"/&quot;/g;    # can't do this you destroy legitimate HTML attributes
	my $p2Htabs = 8;				#pod2HTML uses 8-column tabs
	
	#Replace multiple spaces with tabs. $& is the string that was matched.
	#The number of tabs is equal to the number of spaces / $p2Htabs, plus 1 if there
	#is a remainder, 0 if not. See comments above for tab explanation.
	1 while $inLine =~
		s|  +|"\t" x ( int(length($&) / $p2Htabs)+(length($&) % $p2Htabs != 0 ? 1 : 0) )|e;
		
		
	# kludge to work around the fact that sometimes pod2html uses &quot instead of &quot;

	my @line = split( //, $inLine );
	
	# constants
	my $tabWidth = 4; 
	my $indentFlag = 1;
	my $commentIndentInc = 2;  # zero puts t
	my $maxLineLength = 80;
	
	# counters
	my $HTMLtag = 0;		#is the current character part of an HTML tag?
	my $HTMLchar = 0;		#are we in special character of the form &name; ?
	my $indentSize = 0;
	my $position = 0;		#give number of characters to the left of the pointer
							#	(pointer is after current character)
	my $spacesForTab = 0;	#number of spaces to substitute for a tab

	my $out = "";
	
	foreach my $char ( @line ) {
		$position++;
		
		if( $char eq '<' ) {		#entering an HTML tag
			$HTMLtag = 1;
		}
		if( $char eq '&' ) {		#entering HTML special character
			$HTMLchar = 1;
		}
		
		$position -= ($HTMLtag || $HTMLchar);	#don't count HTML tags or chars for
												#purposes of line breaks and tabs

		if( $char =~ /\s/ ) {
			die "clipline(): The line cannot contain a return" if $char eq "\n";
           
			if( $char eq "\t" ) {
				#emulates tab stops -- the tab might or might not be the full
				#width of the tab field, depending on where it started
				$spacesForTab = ( ($position % $tabWidth) == 0 ?
										1 : ($tabWidth - $position % $tabWidth + 1) );
				
				$char = ' ' x $spacesForTab;
				
				$indentSize += $spacesForTab if $indentFlag == 1;
				$position += $spacesForTab - 1;
			}
			else {
				$indentSize++ if $indentFlag == 1;
			}

#Uncomment to enable wrapping lines after $maxLineLength characters.
#This code might need updating to work correctly
			if ($position > $maxLineLength) {
				$out .= $char . "\n" . ' ' x $indentSize;
				$position = $indentSize + 1;
			}
		}
		else {
			$indentFlag = 0 if $HTMLtag == 0;
		}
						
		if ($char eq "#") {
			$indentSize = $position + $commentIndentInc - 2;  #the 2 is right
		}
		### debug  $char = "$char|$position|" if $char eq "|";
		$out .= $char;
		
		if( $char eq '>' && $HTMLtag == 1 ) {		#leaving an HTML tag
			$HTMLtag = 0;
		}
		if( $char eq ';' && $HTMLchar == 1 ) {		#leaving an HTML char
			$HTMLchar = 0;
			$position++;
		}
	}
	
	$out =~ s/\s*$//;
	
	#this was an attempt to force line breaks to follow the source text, but
	#incoming text has already removed those line breaks.	DME 8/1/2000
	#
	#don't add a <BR> if the line is blank or contains only HTML tags
	#$out .= "<BR>" if( $HTMLpre == 0 && $out ne '' && $out !~ m|^\s*</?.*?>\s*$| );
	
	$out .= "\n";
	
	$HTMLpre = 0 if $out =~ m|</PRE>|i;		#assumes <PRE> ends the line
	
	return $out;
}
