#!/usr/local/bin/perl

#<META TITLE="Query All Of Clint's Media">

my $mode="";
my $DEBUG=0;
my $TITLE="";
my $LOG_FILE="";
my %FIRSTCHARS=();
my $TOPSEARCHURL="";	
my @SKIP_FILE_LIST=();
my $URL_TO_THIS_PROGRAM="";
my $SHORT_NAME=$0; $SHORT_NAME=~s/^.*\///g; $SHORT_NAME=~s/\.([^\.])*$//;	#no extension
my $BOLDREDOFF = "</B></font>";
my $BOLDREDON  = "<font color=ee0000><B>";	#quotes really hurt things here
	#although i have a feeling that in netscape, removing the quotes doesnt
	#help. but in IE it helped ALOT.. no more href="url<font color="red">text</font>"
	#quotes around "red" would actually endquote the href=".... so removing them
	#makes ie render it correctly at least.

##### DETERMINE IF WE'RE $CGI (outputting HTML) OR NOT:
$CGI=defined($ENV{QUERY_STRING});
#DEBUG: print "Content-type: text/html\n\ncgi is $CGI, form is " . %FORM . ", env{query_string} is \"$ENV{QUERY_STRING}\"<br>\n";
if ($CGI) {
	require "./media-constants.pl";
	require "./querystatconstants.pl";
	require "../lib/string.pl";
	require "../lib/syscall.pl";
	require "../lib/counter.pl";
	require "../lib/constants.pl";
	require "../lib/header.pl";
	require "../lib/Parse_Data.pl";
	require "../lib/TabledDataDumper.pl";

	&Print_Header;
	&Parse_Data;

	$TITLE="Clint's Media Search";

	#DEBUG: print &tabledump("media-constants",\%MediaEntities);


	if (($FORM{mode} eq "") || ($FORM{mode} =~ /^catalog$/i)) {
		$mode="catalog";
		@SKIP_FILE_LIST = ("COMICS.HTM", "CONCERTS.HTM", "ALBUM.HTM", "ATARI.HTM",
        		           "INDEX.HTM",   "SEARCH.HTM", "TAPES.HTM",   "VCR.HTM",
                	           "VOICES.HTM");
	} elsif ($FORM{mode} =~ /^search$/i) {
		$mode="search";
		@SKIP_FILE_LIST = (
        		          ### "INDEX.HTM",   "SEARCH.HTM", "TAPES.HTM",   
				);
	}#endif

	$LOG_FILE="$LOGDIR/$SHORT_NAME" . ".log";
	$URL_TO_THIS_PROGRAM="$BASECGIURL/media/$SHORT_NAME" . ".pl";

	$TOPSEARCHURL=$URL_TO_THIS_PROGRAM;
	$TOPSEARCHURL =~ s/\/(.*)$/querystats.pl/;
} else {
	$mode="catalog";
}#endif



##### GET ARGUMENTS:
if (!$CGI && (@ARGV < 3)) { &usage; die @ARGV." is not enough arguments.\nThis sucks"; }

##### DETERMINE TARGET, GENERATE A REGULAR EXPRSSION TO EFFECTIVELY FIND IT::
my $target="";
if ($CGI) { 
	if ($mode eq "catalog") { $target=$FORM{tape};      } 
	else 			{ $target=$FORM{searchfor}; }
} else { 
	$target=$ARGV[0]; 
}#endif
my    $grepfor = "";
my $lookingfor = "";
if (($mode eq "catalog") || ($mode eq "")) {
	   $grepfor = "FOX\#$target"."[^0-9]";                       if ($DEBUG>=1) { print "===> \$grepfor(FINAL)=\"$grepfor\"\n"; }
	$lookingfor = "FOX\#$target";
} elsif ($mode eq "search") {
	   $grepfor = "$target";                       if ($DEBUG>=1) { print "===> \$grepfor(FINAL)=\"$grepfor\"\n"; }
	$lookingfor = "$target";
} else { 
	die("invalid mode of $mode in tape query please alert $MAILTO with this error message");
}#endif
##### Make it safe for regeps:
$grepfor =~ s/^(.)([\?\+\*\[\]])$/$1\$2/;
if ($grepfor eq "^+") { $grepfor="^\+"; }	#argh! seems to have no effect!
if ($grepfor =~ /^([\?\+\*\\\^\$\(\)])$/) { $grepfor="\\$1"; $lookingfor="\\$1"; }
##### If strict, do that:
if ($FORM{strict}) {
	my $strictatron = "[^a-z]";
	$lookingfor = $strictatron . $lookingfor . $strictatron;
	   $grepfor = $strictatron . $grepfor    . $strictatron;
}#endif
#DEBUG: print "mode is $mode, grepfor is $grepfor";



##### CHECK IF THERE WERE ANY FORM INPUTS, DISPLAY MAIN PAGE IF THERE AREN'T:
my $NOINPUTS=0;
if ($CGI) {
	#if (($grepfor eq "") || ($grepfor =~ /$USERNAME\/WWW/)) { $NOINPUTS=1; }
	if ($target eq "") { $NOINPUTS=1; }
	my $titletouse="";
	if ($NOINPUTS) { $lookingfor="nothing"; $titletouse="Query Clint's Video Catalog For Tape Contents"; }
	else { $titletouse=$lookingfor; }
	$TITLE = "$titletouse: Clint Media Query";
}#endif


##### Generate where we're looking for it -- GET OUR FILELIST:
my @filelist=();
if ($CGI) {
	my $files=&do_system_call("ls -1 $WWWDIR/media/*.htm");	
	foreach my $file (split(/\n+/,"$files")) { push(@filelist,$file); }
} else {
	for ($j=1; $j<@ARGV; $j++) { push(@filelist,$ARGV[$j]); }
}#endif
if (0) { foreach (@filelist) { print $q++ . ": \"$_\"\n"; } }

@filelist = sort { 
	$a1=$a; $b1=$b;#goat
	$a1 =~ s/^.*\///g;
	$b1 =~ s/^.*\///g;
	if (defined %{$MediaEntities{$a1}}->{sortname}) { $a1=%{$MediaEntities{$a1}}->{sortname}; }
	if (defined %{$MediaEntities{$b1}}->{sortname}) { $b1=%{$MediaEntities{$b1}}->{sortname}; }
	#print "$a1<=>$b1<BR>\n";
	return($a1 cmp $b1);
} @filelist;

##### HTML/TXT stuff:
my $DIVIDER="";
if ($CGI) {
	##### Start HTML file and stuff:
	print "<html><head><title>$TITLE</title>";
	print qq[<meta name="description" content="Query all of Clint's media: CDs, MP3s, Videos, Comic Books, Concerts, whatever!">];
	print qq[<meta name="keywords" content="cd mp3 video comic book concert vhs music album media Clint">];
	print "</head><body>\n";
	print "\n\n<!-- LOOKING FOR: \"$grepfor\" -->\n\n"; 
	if ($NOINPUTS) { &introduction_page; exit; }
	$DIVIDER="<hr>";
} else {
	$DIVIDER="="x79;
}#endif




######## Actually search for stuff, if that's what we're supposed to do:

&Search_For_Stuff;
if ($CGI) { &footer; }
exit;           				#Just in case there are any doubts.









###############################################################################
sub onegrep {
    local $file = $_[0];
    local $lines=();
    local $line="";
    local $lastline="";
    local $notfound=1;
    local $currentShowName  = "";
    local $currentShowFound = 0;
    local $currentAnchorName="";
    local $currentSectionID="default";
    local $sectionheaderindex=0;
    local %properties;
    local %sectionproperties=();
    local $tmpindex="";
    local $index_lowered=0;
    local $line4analyzing = "";
    my $linesfound=0;
    local $FILEURL="";
    local $SECTIONURL="";

    ##### Get the short filename and the properties for that file
    my $shortFile = $file;
       $shortFile =~ s/^(.*)\///g;
    %properties = %{$MediaEntities{$shortFile}};
    if (defined(%{$properties{sections}->{default}})) { 
		%sectionproperties = %{$properties{sections}->{default}}; 
    }

    ##### Return if this file is in the skipped file list:
    #DEBUG:print &tabledump("file properties for $shortFile",\%properties);
    #DEBUG: print "==> \$file=\"$file\", shortFile=\"$shortFile\", props=".%properties.", props{media}=\"$properties{media}\"<BR>";
    #OLD: foreach my $tmpfile (@SKIP_FILE_LIST) { if ($file =~ /$tmpfile$/i) {if ($CGI) { print "\n<!-- skipping file $tmpfile -->\n"; }return;} }
    #NEW:
    if (($properties{media} eq "0")&&($CGI)){ print "\n<!-- skipping $shortFile -->\n";return;}


    ##### At this point we know we're not skipping it so lets open it:
    open (FILE, "$file") || print("\n\n<h1>Could not open file $file!!!!</h1>\n\n");

    ##### Prep for loop:
    local $index=0, local $maxindex=0, local $maxprintedindex=0;
    while ($lastline=$line, $line=<FILE>) {
	TOPOFLOOPAFTERREAD:

        chomp $line;
        $lines[$index]=$line;				#DEBUG:print "\n<!-- MQXV :Setting lines[$index] to line=\"$line\" -->\n";
	if ($index > $maxindex) { $maxindex=$index; }

	##### Keep track of sections:
	&see_if_section_changed($line);

	CHECKAGAIN:

	##### Go to the next line if our search criterion has not been found, otherwise
	##### keep track of our number of results and continue on...
	#BAD: if ($line !~ /$grepfor/i) { &increment_index_and_read_more_if_necessary; next; }
	#GOOD -- in this situation we don't want to read more if necessary: 
	if ($line !~ /$grepfor/i) { $index++; next; }

	##### we may have foudn it in a link, let's just be sure:
	$line4analyzing = $line;
	$line4analyzing =~ s/<[^<>]*>//g;
	if ($line4analyzing !~ /$grepfor/i) { $index++; next; }

	##### We definitely found it. Keep track of that.
        $numResults++;



	##### If we haven't found a result in this file yet, we must print out "FILE <filename>:"
	##### The same goes for the section... If we haven't found something in the section yet,
	##### we must print out the section name as well:
        if ($notfound) { &printFilenameOut; }
        if (!$currentShowFound) {
            	$currentShowFound=1; 	  	#keep track that we've found this show already
		if (($CGI) && ($TABLE)) { print "</table>\n"; $TABLE=0; }
		if ($currentShowName) { &printnewsectionheader; }
		if ($CGI) { 
			$TABLE=1; $CELL=1; 
			print "</a></B></font>\n";
			print "<table border=0 cellpadding=0 cellspacing=0 align=center>";
			print "<TR>\n<TD>";
			if ($properties{nopre} eq "1") {
				#then do not print the <PRE> tag.
			} else {
				print "<PRE>"; 
			}#endif
		} else { 
			print ":\n"; 
		}
        }#endif



	########## DETERMINE HOW FAR BACK TO GO FOR DISPLAYING THE "PRE-HIT" LINES:
	## skip forward if we are only to show the matched line:
	if (($sectionproperties{"only_show_matched_line"}) 
		|| ($properties{"only_show_matched_line"})) { 
			#&increment_index_and_read_more_if_necessary;#ohoh
			goto PRINTOUTHITLINE; 
	}#endif
	#DEBUG: print "[5]index=$index,maxindex=$maxindex,tmpindex=$tmpindex<BR> ";#



	##### ACTUALLY PRINT THE "PRE-HIT" LINES:
	&decrement_index_to_beginning_of_entity;
	if ($index_lowered) {
		$index_lowered=0; 
		while ($tmpindex < $index) { 
			&prepforprintingandprint($lines[$tmpindex],$tmpindex);
			$tmpindex++;
		}#endwhile
	}#endif

	#DEBUG: print "[10]index=$index,maxindex=$maxindex,tmpindex=$tmpindex<BR> ";#

	##### PRINT OUT OUR "HIT" LINE:
	PRINTOUTHITLINE:
	&checkFirstChars($lines[$index]);	#OH: TODO: gather keys for legend
        &prepforprintingandprint($lines[$index],$index);
	if ($DEBUG>=3) { print "<br><B>Yindex=$index, lines[Yindex]=\"$lines[$index]\"</B>\n"; }	 


	##### skip forward if we are ONLY ONLY to show the matched line:
	if (($sectionproperties{"only_show_matched_line"}) 
		|| ($properties{"only_show_matched_line"})) { 
		goto VERYENDOFLOOP;
	}#endif


	##### After doing this, we are now actually analyzing the NEXT LINE!!!!!!!!
	&increment_index_and_read_more_if_necessary;

	##### PRINT OUT OUR "POST-HIT" LINES:
	$linesfound=0;
	$whilesingleindent=0;
	$whiledoubleindent=0;

	#DEBUG: print "lines[index] is now $lines[$index]<BR>";

	if ($DEBUG>=3) { print "* Nope... checking lines[$index] for $grepfor.. it is:\n\"$lines[$index]\" and line is:\n\"$line\"\n"; }
		if ($lines[$index] =~ /$grepfor/i) { 
		if ($DEBUG>=1) { print "checking again!"; }
		#$lastline=$line;
		#$line=$lines[$index];
			
		if ($DEBUG>=3) { print "line=\"$line\""; }

		#DEBUG: print "Going to check again!!!!";#

		goto CHECKAGAIN; 
	}#endif
	if ($DEBUG>=2) { print "<B>..not found (index=$index,maxindex=$maxindex)</B>\n"; }

	if (($sectionproperties{"go_forward_til_blank_line"})
		|| ($properties{"go_forward_til_blank_line"})) {

		while ($lines[$index] !~ /^\s*$/) { 
			&prepforprintingandprint($lines[$index],$index);
			&increment_index_and_read_more_if_necessary;
			$linesfound++;
		}#endwhile

	} elsif	(($sectionproperties{"go_forward_til_non_indent"}) || 
		        ($properties{"go_forward_til_non_indent"})) {

			$whilesingleindent=1;

	} elsif (&double_indent($lines[$index])) {

		if (($properties{go_forward_on_double_indent}) || ($sectionproperties{go_forward_on_double_indent}))
		{
			$whiledoubleindent=1;
		}

	} elsif (&single_indent($lines[$index])) {

		if (($properties{go_forward_on_single_indent}) || ($sectionproperties{go_forward_on_single_indent})) {
			$whilesingleindent=1;
		}

	}#endif



	if ($whiledoubleindent) {
	        while (&double_indent($lines[$index])) {	            if ($DEBUG>=2) { print "DI: "; }
	            &prepforprintingandprint($lines[$index],$index);
		    #OLD: #&increment_index_and_read_more_if_necessary({dontread=>1});
		    &increment_index_and_read_more_if_necessary;
		    $linesfound++;
	        }#endif
		if ($linesfound>0) { goto TOPOFLOOPAFTERREAD; }	#sucky!	#OH need?
	} elsif ($whilesingleindent) {
	        while (&single_indent($lines[$index])) {	            if ($DEBUG>=2) { print "DI: "; }
	            &prepforprintingandprint($lines[$index],$index);
		    #OLD: #&increment_index_and_read_more_if_necessary({dontread=>1});
		    &increment_index_and_read_more_if_necessary;
		    $linesfound++;
	        }#endif
		if ($linesfound>0) { goto TOPOFLOOPAFTERREAD; }	#sucky!		#OH need?
	}

	VERYENDOFLOOP:
    }#endwhile



    close (FILE);



    @lines=();          #This really shouldn't be necessary!
                        #But it does NOT renew every time onegrep is called!

    if ($CELL)  { print "</TD></TR>"; $CELL=0;  }
    if ($TABLE) { print "</table>\n"; $TABLE=0; }
}#endsub onegrep
###############################################################################

###############################################################################################################
sub decrement_index_to_beginning_of_entity {
        $tmpindex=$index;           #pre-goback-index

	$whilesingleindent=0;
	$whiledoubleindent=0;

	## if the line's double-indented and we're supposed to go back...
        if (&double_indent($line)) {
		if ($DEBUG>=1) { my $line2=$line;chomp $line2;print "Result found on double-indented line $index of file $file: \"$line2\"...\n"; }

		if (($properties{go_back_on_double_indent}) || ($sectionproperties{go_back_on_double_indent})) 	{
		    $whiledoubleindent=1;
		} elsif (($properties{go_back_on_single_indent}) || ($sectionproperties{go_back_on_single_indent})) {
		    $whilesingleindent=1;
		}#endif

	## if the line's sigle-indented and we're supposed to go back...
	} elsif (&single_indent($line)) {
		if (($properties{go_back_on_single_indent}) || ($sectionproperties{go_back_on_single_indent})) 	{
			#print "going back on single indent........<BR>";#OH

			$whilesingleindent=1;
		}#endif

	}#endif

	#------------------

	#print "<B>whilesingleindent=$whilesingleindent,whiledoubleindent=$whiledoubleindent</B><BR>";

	if ($whilesingleindent) {
			while (&single_indent($lines[$tmpindex]) && ($tmpindex>$sectionheaderindex)) { 
			    $tmpindex--; 
			    $index_lowered=1;
			    if ($DEBUG{goback}>=3) { print "[2]Lowering index...<BR>"; }
			}	
	} elsif ($whiledoubleindent) {
		    while (&double_indent($lines[$tmpindex]) && ($tmpindex>$sectionheaderindex)) { 
			$tmpindex--; 
			$index_lowered=1;
			if ($DEBUG{goback}>=3) { print "[1]Lowering index...<BR>"; }
		    }
	}#endif

	if ((($DEBUG>=1)||($DEBUG{goback}))&&($index-$tmpindex > 0)) { print "[2]Went back ".($index-$tmpindex)." lines...\n"; }
	if  (($DEBUG>=1)||($DEBUG{goback})) { if ($sectionproperties{go_back_til_blank_line}) {print "gobacktilblank is true!!!!!!!! went back ".($index-$tmpindex)." lines  index=$index lines[$index]=\"$lines[$index]!\n";} }

	#------------------


	## if we're supposed to go back til a blank line.....
	if ($sectionproperties{go_back_til_blank_line}) {	#then we need to go back even farther!
		if ($DEBUG>=1) { print "going back til blank line...: \$lines[$tmpindex] is \"$lines[$tmpindex]\"<br>"; }
		while (($lines[$tmpindex] !~ /^\s*$/)&&($tmpindex>$sectionheaderindex)) { 
			$tmpindex--; 
			$index_lowered=1;
			if ($DEBUG{goback}>=3) { print "[3]Lowering index...<BR>"; }
		}
	}#endif

	if (($DEBUG>=1) && (($index-$tmpindex) > 0)) { print "[3]Went back ".($index-$tmpindex)." lines...\n"; }
}#endsub decrement_index_to_beginning_of_entity
###############################################################################################################



##################################################################################################
sub increment_index_and_read_more_if_necessary {
	#ASSUMES local $line;
	#ASSUMES local $index;
	#ASSUMES local $maxindex;
	#ASSUMES filehandle FILE;
	my $criteria = $_[0];

	$index++;

	### $DEBUGL=1;

	if ($DEBUGL>=1) { print qq[\n<!-- PRE: Just incremented index to $index (maxindex=$maxindex)\n-->]; }

	if ($index > $maxindex) {
		$maxindex=$index;
		if ($criteria->{dontread}) {	#todo remove this part if increment_index_and_read_more_if_necessary is
			#don't do anything	#never being called with any criterion anymore
			goto TOPOFLOOPAFTERREAD;#dirty dirty dirty! bad!
		}
		$lastline=$line;
		$line=<FILE>;
		$line =~ s/[\r\n]//g;
		$lines[$index]=$line;
		if ($DEBUG>=3) { print "index now is $index : Just had to read in line \"$line\" as index $index"; }
	}#endif

	if ($DEBUGL>=1) { print qq[\n<!-- POST: maxindex=$maxindex\tline="$line"\n-->]; }

}#endsub increment_index_and_read_more_if_necessary
##################################################################################################


##########################################################################################################################
sub see_if_section_changed {
	my $DEBUG=0;	#
	my $line=$_[0];

	if ($DEBUG>=5) { print "<B>checking section change[$index]: \"$line\"...</b><BR>"; }

	##### Keep track of sections:
        if ($line =~ /<a[^>]*name=\"([^\"]+)\"[^>]*>/i) {
            $currentShowName   =  $1;
	    $currentAnchorName =  $currentShowName;
            $currentShowFound  =  0;
	    #NO: $currentAnchorName =~ s/\"//g;
	
	    $sectionheaderindex=$index;

	    ##### If a section id is defined, check if we have properties defined for that id:
	    if ($line =~ /<a[^>]*id=\"([^\"]+)\"/i) {
		$currentSectionID=$1;
		#DEBUG:	print "<B>setting currentsectionid to $currentSectionID...</b>";#OH
	    } else {
		$currentSectionID="default";	#allows default properties
	    }#endif

#	    $DEBUG{sectionproperties}="1";#OHohoh

	    if (defined($properties{sections}->{$currentSectionID})) {
		%sectionproperties = %{$properties{sections}->{$currentSectionID}};
		if (($DEBUG>=1)||($DEBUG{sectionproperties})) { print &tabledump("properties for $currentShowName",\%sectionproperties); }
	    } else {
		%sectionproperties = {};
	    }#endif
        }#endif
}#endsub see_if_section_changed
##########################################################################################################################

#####################################################################################################################
sub printFilenameOut {
            	$notfound=0;   
		my $file4print = $file;
		   $file4print =~ s/^.*\///g;
		print "$DIVIDER\n".($CGI?"<font size=5 face=\"Arial, helvetica, sans-serif\"><B>":"")."FILE ";
		if ($CGI) {
			$FILEURL=$file; 
			#$FILEURL =~ s/$WWWDIR/\/~$USERNAME/; 
			$FILEURL =~ s/$WWWDIR//i;					#2009/sheer
			#print "fileurl = $FILEURL <BR>\n";
			print "<a href=\"$FILEURL\">";
		}#endif
		print uc($file4print); 	if ($CGI) {print "</a>";}
		print ":";
		print ($CGI?"</font><font size=3 face=\"Arial, helvetica, sans-serif\">":"");
		if ($CGI) { 
			print "&nbsp;" x 5;
			print "(".$properties{description}.")" if $properties{description}; 
		}#endif
		print ($CGI?"</font><font size=5>":"");
		#print ":";
		print ($CGI?"</B></font>":"");
		print "\n";
		if ($CGI) { print "<br>\n\n"; }
}#endsub printFilenameOut
#####################################################################################################################

##########################################################################################################################
sub prepforprintingandprint {	#prep4printing
my $s   = $_[0];
my $idx = $_[1];

my $DEBUG=0;

if ($DEBUG) {  print "<!-- PRE: s=$s -->"; }
if ($DEBUG>=3) {my ($package, $filename, $line) = caller;$s = "\n<BR><B>$line" . "::Zindex=$index;</B> $s<BR>\n"; }#endif

##### strip out bad html since a tag may not end til the next line.....
$s =~ s/<[^<>]*$//;
$s =~ s/^[^<>]*>$//;

##### strip out name from anchor tags effectively making them not do anything:
##### this also helps us from displaying invisible results...
##### (ie search criterion found in a URL or hidden input)
$s =~ s/(<a[^>]*)(name="[^"]+")([^>]*>)/$1$3/;
##$s =~ s/(<a[^>]*)(id="[^"]+")([^>]*>)/$1$3/;

if ($DEBUG) { print "<!-- POST: s=$s -->"; }

#### should work but doesn't:
#if ($properties{filelist} eq "1") { 
#	$s =~ s/"/&iquest;/g; 
#	$s =~ s/¿/&iquest;/g; 
#}

##### Do not allow relative URLs here as they will not work:
$s =~ s/href=\"([a-z])/href=\"$BASEURL\/media\/$1/i;

##### Make FOX#s into links:
if ($s =~ /FOX\#[0-9]/) {
	my $A="<a target=\"_newsearch";
	my $B="\" href=\"$URL_TO_THIS_PROGRAM";
	my $C="?mode=catalog&tape=";
	my $D="\">";
	my $E="</a>";
	$s =~ s/(FOX\#)([0-9]+)/$A$2$B$C$2$D$1$2$E/ig;
}#endif

##### Highlight results:
###OLD: my $swithnolinks=$s;
###OLD: while ($swithnolinks =~ /<.*>/) { $swithnolinks =~ s/<[^>]*>//g; }
###OLD: #DEBUG: print "swithnolinks is $swithnolinks";
###OLD: if ($swithnolinks =~ /$lookingfor/i) { $s =~ s/($lookingfor)/$A$1$B/gi; } #could still mess up
#OLD: if (($s =~ /$lookingfor/i) && ($s !~ /[<>]/)) { $s =~ s/($lookingfor)/$A$1$B/gi; } #could still mess up
#NEW:
if (($s =~ /$lookingfor/i) && ($s !~ /name="[^"]?$lookingfor[^"]*"/)
	&& ($s !~ /src="[^"]*?$lookingfor[^"]*"/)
) { 
	$s =~ s/($lookingfor)/$BOLDREDON$1$BOLDREDOFF/i; #could still mess up

	#DEBUG: if (1) { $s = "[$currentSectionID] =>" . $s; }
}#endif

#DEBUG: if (($DEBUG>=3)||($DEBUG{caller})) { my ($package, $filename, $line) = caller;	print "<B>from#$line" . "::index=$index;</B> "; }



##### Do not allow relative image links as they will not work:
$s =~ s/src=\".*?\/pics\//src="$BASEURL\/pics\//i;




##### only print the line if this index hasn't yet been printed:
if ($idx > $maxprintedindex) {
	$maxprintedindex=$idx;
	if ($DEBUG>=1) { print "==> PRINTING [idx=$idx,max=$maxprintedindex]: "; }
	print $s;
	print "\n";
} elsif (($DEBUG>=1)||($DEBUG{caller})) {
	print "==> NOT PRINTING [idx=$idx,max=$maxprintedindex]: $s\n";
}#endif

#OLD: return($s);
}#endsub prepforprintingandprint
##########################################################################################################################


#####################################################################
sub checkFirstChars {
#ASSUMES GLOBAL %FIRSTCHARS;
#($lines[$index]);
}#endsub checkFirstChars
#####################################################################

####################################################################
sub usage {
print qq[
    USAGE: vcrgrep (255) *.htm
                   ^^^^^ grepfor text must be in parenthesis
];
}#endsub usage
####################################################################

########################################################################
sub double_indent {
    if ($DEBUG>=3) { print "* Checking double_indent, line=$_[0]\n"; }
    if ($_[0] =~ /^.\s{7}/) { return(1); }
    return(0);
}#endsub double_indent
########################################################################

#####################################################################################
sub single_indent {
    if ($DEBUG>=3) { print "* Checking single line=$_[0]\n"; }

    #### Must check for any character I would put in column 1 or 2...
    if ($_[0] =~ /^.[\s\-\+\?\@\!\*\%\$234ACDFLMobdsw]\s\s[^\s]/) { return(2); }
    if ($_[0] =~ /^.[\s\-\+\?\@\!\*\%\$234ACDFLMobdsw]\s\s/)      { return(1); }
    return(0);
}#endsub single_indent
#####################################################################################

########################################################
sub footer {
my $criteria = $_[0];
my $counter  = 1;
my $links    = 1;

###print "</font>";

if ($criteria->{counteronly}) { $counter=1; $links=0; }
if ($criteria->{linksonly})   { $counter=0; $links=1; }

if ($counter) {	print &counter({begintext=>'</font><B>You are visitor number',
			endtext=>'.</b>'}); };

if ($counter && $links) { print "<BR>"x2; };

if ($links) {
	print qq[
	<font size=2>
	<a href="mailto:$MAILTO">Clint's mail</a><br>
	<a href="$BASEURL/media">Clint's media catalogs</a><br>
	</font>];
	print qq[
<table width=100% border=0><Tr valign=top><td align=center>
<script type="text/javascript"><!--
google_ad_client = "pub-1303586900976050";
/* ACM Footer, 728x90, created 6/13/08 */
google_ad_slot = "9449894613";
google_ad_width = 728;
google_ad_height = 90;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</td></tr></table>
	];

}#endif


}#endsub footer
########################################################

################################################################
sub searchqueryform {
my $criteria = $_[0];
my $simple = $criteria->{simple};

print qq[<form method=get>];

if (!$simple) {
	print qq[<table align=center border=0 cellspacing=1 cellpadding=2>
<tr valign=middle>
<td align=center><font size=6><b>Search All Of Clint's Media</b></font></TD>
</tr>
<tr valign=middle>
<td align=center>];
}#endif


if ($simple) {
	my $size=length($FORM{searchfor}) || 5;  #OH?
	print qq[<input type=text name="searchfor" value="$FORM{searchfor}" size=$size maxlength=80>];
} else {
	print qq[<input type=text name="searchfor" size=40 maxlength=80>];
}#endif


print qq[<input type=hidden name=mode value=search>];

if ($simple) { 
	my $checked="";
	if ($FORM{strict}) { 
		$checked="checked";
		if ($FORM{strict}) { print qq[<input type=hidden name=was_strict value=1>]; }
	}
	print qq[<input type=submit value="Try Again">
	<font size=2>Strict:</font><input type="checkbox" name="strict" value="1" $checked>];    
} else { 
	print qq[<input type=submit value="Search Media">]; 
}


if (!$simple) {
	print qq[</td>
</tr>

<tr valign=middle>
<td align=center><nobr><input type=checkbox name="strict" value="1"><B>Use Strict Search.</B></nobr>
Use this to prevent hits within words, for example this would let you search for
&quot;Ween&quot; without returning songs about &quot;halloWEEN&quot;, or search
for songs by the band &quot;ALL&quot; without returning &quot;MetALLica&quot; songs.

</td>
</tr>

<tr valign=middle>
<td align=center>
<BR>
<B><a target="_regex" href="$BASEURL/voices/grepdoc.htm#RegEx">Regular expressions</a> *ARE* allowed.</b><BR>
<B><U>Try to be specific.</u></B>  &nbsp; Short searches will give <i>too</i> many results.<BR>


<BR>If you want to see if I tape a certain <B>television show or cartoon</b>,<BR>
notice the results in (or simply go to) the file <a href="$BASEURL/media/vcr.htm">VCR.HTM</a>.
</td></tr></table>];
}#endif

print qq[</form>];

return("");	#for wrapper func
}#endsub searchqueryform
################################################################



################################################################
sub catalogqueryform {
my $criteria = $_[0];
my $simple = $criteria->{simple};

##### start form

print qq[<form method=get>];

if (!$simple) {
	print qq[<table align=center border=0 cellspacing=1 cellpadding=2>
	<tr valign=middle>
	<td align=center><font size=5><b>List The Shows On One Of Clint's Tapes</b></font></TD>
	</tr>
	<tr valign=middle>
	<td align=center><B>Enter tape # (FOX#xxx) (ie "1","2","5","$LAST_VALID_TAPE"):</b></td>
	</tr>
	<tr valign=middle>
	<td align=center>];
}#endif

print qq[<input type=text name="tape" size=3 value="$FORM{tape}" maxlength=3>];
print qq[<input type=hidden name=mode value=catalog>];

if ($simple) { print qq[<input type=submit value="Try Again">]; 		   } 
else 	     { print qq[<input type=submit value="What shows are on that tape?">]; }

if (!$simple) {
	print qq[</td>
	</tr>
	<tr valign=middle>
	<td align=center>Valid tape numbers are approximately any number between 1 and $LAST_VALID_TAPE.<br>
	To find out which tape #s are valid (FOX#s only), refer my personal file:
	<a target="_tapes" href="$BASEURL/media/tapes.htm">tapes.htm</a>.</td>
	</tr></table>];
}#endif

print qq[</form>];

return("");	#for wrapper func
}#endsub catalogqueryform
################################################################

#################################################################################################
sub introduction_page {
	print qq[<table align=center width=100% border=0>];
	print qq[<tr valign="center"><td align=center colspan=2>];
	print qq[
<script type="text/javascript"><!--
google_ad_client = "pub-1303586900976050";
/* ACM Media Query, 728x90, created 6/13/08 */
google_ad_slot = "3285839484";
google_ad_width = 728;
google_ad_height = 90;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
];
	print qq[</td></tr>];
	print qq[<tr valign="center">];
	print qq[<TD align=left>];
	print qq[<font size=5><B><a href="$TOPSEARCHURL">View 
	Most Popular Searches Here</a></b></font>];
	print qq[</td>];
	print qq[<td align=right>];
	&footer({counteronly=>1});
	print qq[</td>];
	print qq[</tr></table>];
	&searchqueryform;
	print "<BR>" x 1;
	print "<BR>" x 1;
	&catalogqueryform;
	&footer({linksonly=>1}); 
}#endsub introduction_page
#################################################################################################

###################################################################
sub whateverqueryform {
	my ($options)=$_[0];
	#foreach (@options) {print "option is $_ ";}#. @options;
	if ($mode eq "catalog") {
		my $r=&catalogqueryform($options);
		return($s);
	} elsif ($mode eq "search") {
		return  &searchqueryform($options);
	} else {
		print "BUG NUMBER 54433225. REPORT TO CLINT.";
	}#endif
}#endif
###################################################################

#########################################################################################
sub printgoback {
##### Go through each file and look for what we're looking for:

print qq[<table border=0 cellpadding=0 cellspacing=0 width="100%">
<tr valign=top><td align=center colspan=3>
<script type="text/javascript"><!--
google_ad_client = "pub-1303586900976050";
/* ACM Media Query, 728x90, created 6/13/08 */
google_ad_slot = "3285839484";
google_ad_width = 728;
google_ad_height = 90;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</td></tr>
<tr valign=top>
<td align=left><B><a href="$URL_TO_THIS_PROGRAM">Back</a> to search engine...</a></B></td>
<td align=center><B>[<a href="$TOPSEARCHURL">Top Searches</a>]</B></td>
<td align=right>];
print &whateverqueryform({simple=>1});
print qq[</td></tr></table>];
}#endsub printgoback
#########################################################################################

#############################################################################################
sub Search_For_Stuff {
&printgoback;
print qq[<table border=0 cellpadding=0 cellspacing=0 align=center>];
print qq[<tr valign=middle><td align=center>];
if    ($mode eq "catalog") { print "<font size=7><B>$lookingfor</B><br>"; } 
elsif ($mode eq "search")  { print "<font size=5>Searching for: </font><font size=6><B>\"$lookingfor\"</B><br>"; }
print qq[</td></tr></table>\n];

local $numResults=0;
local $TABLE=0;
local $CELL=0;
foreach (@filelist) { &onegrep($_); }
print $DIVIDER."\n";

if    ($mode eq "catalog") { $tmpsize=6; } 
elsif ($mode eq "search")  { $tmpsize=5; } 

my $content="*** $numResults results found with \"$lookingfor\" ***";

&logrequest($LOG_FILE,$lookingfor);	#uses numResults

print $CGI?"<p align=center><font size=$tmpsize><B>$content</font></b></p>\n\n":"$content";
}#endsub Search_For_Stuff
#############################################################################################


#########################################################################################################
sub logrequest {
my ($file)    = $_[0];
my ($request) = $_[1];

##### if the logfile is accidentally created with the wrong permissions (forgot to umask),
##### uncomment this block out to make it accessible to group only
if (-e $file) {
	my $permissions="777";	#644 is secure, 777 to edit
	#my $permissions="644";	#644 is secure, 777 to edit
	&do_system_call("chmod $permissions $file");
}#endif

if (!open(LOG,">>$file")) {
	print "<BR><BR>error: could not open logfile $file!!!!!<BR><BR>"; 
}#endif

#DEBUG: map { print "<BR>$_ = $ENV{$_}" } keys %ENV;

print LOG join ("$DELIMITER", 
    (
	"REQ" . $SUB_DELIMITER . $request,
	"IP"  . $SUB_DELIMITER . $ENV{REMOTE_ADDR},
	"M"   . $SUB_DELIMITER . $ENV{REQUEST_METHOD},
	"F"   . $SUB_DELIMITER . $numResults,
    ));
print LOG "\n";

close(LOG);

}#endsub logrequest
#########################################################################################################

############################################################################################
sub scrubAnchorName {
my $s = $_[0];

##### Translate "ql" into quick list:
if ($s =~ /^ql$/i) { return("quick list"); }

##### Strip "episodes" or "eps" from end
$s =~ s/Epi?s?o?d?e?s$//;

##### Insert spaces when it goes lowercase-capital IF no non-alphabet chars:
if ($s =~ /^[a-z]+$/i) { $s =~ s/([a-z])([A-Z])/$1 $2/g; }

##### convention-- for my anchor names, i use the following abbreviations:
	#	"--_" for ": " 
	#	"_"   for for " "
$s =~ s/\-\-_/: /g;
$s =~ s/_/ /g;	#do this last

##### make "clint's" and "carolyn's"
foreach ("clint","carolyn","henson") { 
	$s =~  s/^($_)s\s/$1\'s /gi; 
	$s =~ s/\s($_)s\s/ $1\'s /gi; 
}#endforeach

##### Add aspostrophes like so too:
$s =~ s/ ive / I've /g;

##### Return the scrubbed name:
return($s);
}#endsub scrubAnchorName
############################################################################################

####################################################################################################################################################################
sub printnewsectionheader {
print ($CGI?"<font size=4><B>SECTION ":"SECTION ");
if ($CGI) {
	$SECTIONURL = $FILEURL . "\#$currentAnchorName";
	#$SECTIONURL =~ s/\#.*$//; $SECTIONURL .= "\#$currentAnchorName";
	print "<a href=\"$SECTIONURL\">".&scrubAnchorName($currentShowName)."</a>:\n";
} else {
	print &scrubAnchorName($currentShowName) . ":\n";
}#endif
}#endsub printnewsectionheader
####################################################################################################################################################################


#EOF
