###########################################################################
#
# HTMLPlugin.pm -- basic html plugin
#
# A component of the Greenstone digital library software
# from the New Zealand Digital Library Project at the 
# University of Waikato, New Zealand.
#
# Copyright (C) 1999 New Zealand Digital Library Project
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
#
###########################################################################

# 
# Note that this plugin handles frames only in a very simple way
# i.e. each frame is treated as a separate document. This means
# search results will contain links to individual frames rather
# than linking to the top level frameset.
# There may also be some problems caused by the _parent target
# (it's removed by this plugin)
#

package HTMLPlugin;

use ReadTextFile;
use HBPlugin;
use ghtml;
use unicode;
use util;
use XMLParser;

use Image::Size;
use File::Copy;

sub BEGIN {
    @HTMLPlugin::ISA = ('ReadTextFile', 'HBPlugin');
}

use strict; # every perl program should have this!
no strict 'refs'; # make an exception so we can use variables as filehandles

my $arguments =
    [ { 'name' => "process_exp",
	'desc' => "{BasePlugin.process_exp}",
	'type' => "regexp",
	'deft' =>  &get_default_process_exp() },
      { 'name' => "block_exp",
	'desc' => "{BasePlugin.block_exp}",
	'type' => 'regexp',
	'deft' =>  &get_default_block_exp() },
      { 'name' => "nolinks",
	'desc' => "{HTMLPlugin.nolinks}",
	'type' => "flag" },
      { 'name' => "keep_head",
	'desc' => "{HTMLPlugin.keep_head}",
	'type' => "flag" },
      { 'name' => "no_metadata",
	'desc' => "{HTMLPlugin.no_metadata}",
	'type' => "flag" },
      { 'name' => "metadata_fields",
	'desc' => "{HTMLPlugin.metadata_fields}",
	'type' => "string",
	'deft' => "Title" },
      { 'name' => "hunt_creator_metadata",
	'desc' => "{HTMLPlugin.hunt_creator_metadata}",
	'type' => "flag" },
      { 'name' => "file_is_url",
	'desc' => "{HTMLPlugin.file_is_url}",
	'type' => "flag" },
      { 'name' => "assoc_files",
	'desc' => "{HTMLPlugin.assoc_files}",
	'type' => "regexp",
	'deft' => &get_default_block_exp() },
      { 'name' => "rename_assoc_files",
	'desc' => "{HTMLPlugin.rename_assoc_files}",
	'type' => "flag" },
      { 'name' => "title_sub",
	'desc' => "{HTMLPlugin.title_sub}",
	'type' => "string", 
	'deft' => "" },
      { 'name' => "description_tags",
	'desc' => "{HTMLPlugin.description_tags}",
	'type' => "flag" },
      # retain this for backward compatibility (w3mir option was replaced by
      # file_is_url)
      { 'name' => "w3mir",
#	'desc' => "{HTMLPlugin.w3mir}",
	'type' => "flag",
	'hiddengli' => "yes"},
      { 'name' => "no_strip_metadata_html",
	'desc' => "{HTMLPlugin.no_strip_metadata_html}",
	'type' => "string",
	'deft' => "",
	'reqd' => "no"},
      { 'name' => "sectionalise_using_h_tags",
	'desc' => "{HTMLPlugin.sectionalise_using_h_tags}",
	'type' => "flag" },
      { 'name' => "use_realistic_book",
        'desc' => "{HTMLPlugin.tidy_html}",
	'type' => "flag"},
      { 'name' => "old_style_HDL",
        'desc' => "{HTMLPlugin.old_style_HDL}",
	'type' => "flag"}
      ];

my $options = { 'name'     => "HTMLPlugin",
		'desc'     => "{HTMLPlugin.desc}",
		'abstract' => "no",
		'inherits' => "yes",
		'args'     => $arguments };


sub HB_read_html_file {
    my $self = shift (@_);
    my ($htmlfile, $text) = @_;
    
    # load in the file
    if (!open (FILE, $htmlfile)) {
	print STDERR "ERROR - could not open $htmlfile\n";
	return;
    }

    my $foundbody = 0;
    $self->HB_gettext (\$foundbody, $text, "FILE");
    close FILE;
    
    # just in case there was no <body> tag
    if (!$foundbody) {
	$foundbody = 1;
	open (FILE, $htmlfile) || return;
	$self->HB_gettext (\$foundbody, $text, "FILE");	
	close FILE;
    }
    # text is in utf8
}		

# converts the text to utf8, as ghtml does that for &eacute; etc.
sub HB_gettext {
    my $self = shift (@_);
    my ($foundbody, $text, $handle) = @_;
    
    my $line = "";
    while (defined ($line = <$handle>)) {
	# look for body tag
	if (!$$foundbody) {
	    if ($line =~ s/^.*<body[^>]*>//i) {
		$$foundbody = 1;
	    } else {
		next;
	    }
	}
	
	# check for symbol fonts
	if ($line =~ m/<font [^>]*?face\s*=\s*\"?(\w+)\"?/i) {
	    my $font = $1;
	    print STDERR "HBPlug::HB_gettext - warning removed font $font\n" 
		if ($font !~ m/^arial$/i);
	}

	$$text .= $line;
    }

    if ($self->{'input_encoding'} eq "iso_8859_1") {
	# convert to utf-8
	$$text=&unicode::unicode2utf8(&unicode::convert2unicode("iso_8859_1", $text));
    }
    # convert any alphanumeric character entities to their utf-8
    # equivalent for indexing purposes
    #&ghtml::convertcharentities ($$text);

    $$text =~ s/\s+/ /g; # remove \n's
}

sub HB_clean_section {
    my $self = shift (@_);
    my ($section) = @_;

    # remove tags without a starting tag from the section
    my ($tag, $tagstart);
    while ($section =~ m/<\/([^>]{1,10})>/) {
	$tag = $1;
	$tagstart = index($section, "<$tag");
	last if (($tagstart >= 0) && ($tagstart < index($section, "<\/$tag")));
	$section =~ s/<\/$tag>//;
    }
    
    # remove extra paragraph tags
    while ($section =~ s/<p\b[^>]*>\s*<p\b/<p/ig) {}
    
    # remove extra stuff at the end of the section
    while ($section =~ s/(<u>|<i>|<b>|<p\b[^>]*>|&nbsp;|\s)$//i) {}
    
    # add a newline at the beginning of each paragraph
    $section =~ s/(.)\s*<p\b/$1\n\n<p/gi;
    
    # add a newline every 80 characters at a word boundary
    # Note: this regular expression puts a line feed before
    # the last word in each section, even when it is not
    # needed.
    $section =~ s/(.{1,80})\s/$1\n/g;
    
    # fix up the image links
    $section =~ s/<img[^>]*?src=\"?([^\">]+)\"?[^>]*>/
	<center><img src=\"$1\" \/><\/center><br\/>/ig;
    $section =~ s/&lt;&lt;I&gt;&gt;\s*([^\.]+\.(png|jpg|gif))/
	<center><img src=\"$1\" \/><\/center><br\/>/ig;

    return $section;
}

# Will convert the oldHDL format to the new HDL format (using the Section tag)	
sub convert_to_newHDLformat
{
    my $self = shift (@_);
    my ($file,$cnfile) = @_;
    my $input_filename = $file;
    my $tmp_filename = $cnfile;
    
    # write HTML tmp file with new HDL format
    open (PROD, ">$tmp_filename") || die("Error Writing to File: $tmp_filename $!");
    
    # read in the file and do basic html cleaning (removing header etc)
    my $html = "";
    $self->HB_read_html_file ($input_filename, \$html);
    
    # process the file one section at a time
    my $curtoclevel = 1;
    my $firstsection = 1;
    my $toclevel = 0;
    while (length ($html) > 0) {
	if ($html =~ s/^.*?(?:<p\b[^>]*>)?((<b>|<i>|<u>|\s)*)&lt;&lt;TOC(\d+)&gt;&gt;\s*(.*?)<p\b/<p/i) {
	    $toclevel = $3;
	    my $title = $4;
	    my $sectiontext = "";
	    if ($html =~ s/^(.*?)((?:<p\b[^>]*>)?((<b>|<i>|<u>|\s)*)&lt;&lt;TOC\d+&gt;&gt;)/$2/i) {
		$sectiontext = $1;
	    } else {
		$sectiontext = $html;
		$html = "";
	    }

	    # remove tags and extra spaces from the title
	    $title =~ s/<\/?[^>]+>//g;
	    $title =~ s/^\s+|\s+$//g;

	    # close any sections below the current level and
	    # create a new section (special case for the firstsection)
	    print PROD "<!--\n";
	    while (($curtoclevel > $toclevel) ||
		   (!$firstsection && $curtoclevel == $toclevel)) {
		$curtoclevel--;
		print PROD "</Section>\n";
	    }
	    if ($curtoclevel+1 < $toclevel) {
		print STDERR "WARNING - jump in toc levels in $input_filename " . 
		    "from $curtoclevel to $toclevel\n";
	    }
	    while ($curtoclevel < $toclevel) {
		$curtoclevel++;
	    }

	    if ($curtoclevel == 1) {
	    	# add the header tag
		print PROD "-->\n";
    		print PROD "<HTML>\n<HEAD>\n<TITLE>$title</TITLE>\n</HEAD>\n<BODY>\n";
		print PROD "<!--\n";
	    }
	    
	    print PROD "<Section>\n\t<Description>\n\t\t<Metadata name=\"Title\">$title</Metadata>\n\t</Description>\n";
	    
	    print PROD "-->\n";
	    
	    # clean up the section html
	    $sectiontext = $self->HB_clean_section($sectiontext);

	    print PROD "$sectiontext\n";	 

	} else {
	    print STDERR "WARNING - leftover text\n" , $self->shorten($html), 
	    "\nin $input_filename\n";
	    last;
	}
	$firstsection = 0;
    }
    
    print PROD "<!--\n";
    while ($curtoclevel > 0) {
	$curtoclevel--;
	print PROD "</Section>\n";
    }
    print PROD "-->\n";
    
    close (PROD) || die("Error Closing File: $tmp_filename $!");
    
    return $tmp_filename;
}		

sub shorten {
    my $self = shift (@_);
    my ($text) = @_;

    return "\"$text\"" if (length($text) < 100);

    return "\"" . substr ($text, 0, 50) . "\" ... \"" . 
	substr ($text, length($text)-50) . "\"";
}

sub convert_tidy_or_oldHDL_file
{
    my $self = shift (@_);
    my ($file) = @_;
    my $input_filename = $file;
    
    if (-d $input_filename)
    {
    	return $input_filename;
    }
    
    # get the input filename
    my ($tailname, $dirname, $suffix) = &File::Basename::fileparse($input_filename, "\\.[^\\.]+\$");
    my $base_dirname = $dirname;
    $suffix = lc($suffix);   
    
    # derive tmp filename from input filename
    # Remove any white space from filename -- no risk of name collision, and
    # makes later conversion by utils simpler. Leave spaces in path...
    # tidy up the filename with space, dot, hyphen between
    $tailname =~ s/\s+//g; 
    $tailname =~ s/\.+//g;
    $tailname =~ s/\-+//g;
    # convert to utf-8 otherwise we have problems with the doc.xml file
    # later on
    &unicode::ensure_utf8(\$tailname);
    
    # softlink to collection tmp dir
    my $tmp_dirname = &util::filename_cat($ENV{'GSDLCOLLECTDIR'}, "tidytmp");
    &util::mk_dir($tmp_dirname) if (!-e $tmp_dirname);
    
    my $test_dirname = "";
    my $f_separator = &util::get_os_dirsep();
    
    if ($dirname =~ m/import$f_separator/)
    {
    	$test_dirname = $'; #'
	
	#print STDERR "init $'\n";
	
	while ($test_dirname =~ m/[$f_separator]/)
	{
	    my $folderdirname = $`;
	    $tmp_dirname = &util::filename_cat($tmp_dirname,$folderdirname);
	    &util::mk_dir($tmp_dirname) if (!-e $tmp_dirname);
	    $test_dirname = $'; #'
	}
    }
    
    my $tmp_filename = &util::filename_cat($tmp_dirname, "$tailname$suffix");
    
    # tidy or convert the input file if it is a HTML-like file or it is accepted by the process_exp
    if (($suffix eq ".htm") || ($suffix eq ".html") || ($suffix eq ".shtml"))
    {   
    	#convert the input file to a new style HDL
    	my $hdl_output_filename = $input_filename;
    	if ($self->{'old_style_HDL'})
    	{
	    $hdl_output_filename = &util::filename_cat($tmp_dirname, "$tailname$suffix");
	    $hdl_output_filename = $self->convert_to_newHDLformat($input_filename,$hdl_output_filename);
    	}
	
	#just for checking copy all other file from the base dir to tmp dir if it is not exists
	opendir(DIR,$base_dirname) or die "Can't open base directory : $base_dirname!";
	my @files = grep {!/^\.+$/} readdir(DIR);
	close(DIR);

	foreach my $file (@files) 
	{
	    my $src_file = &util::filename_cat($base_dirname,$file);
	    my $dest_file = &util::filename_cat($tmp_dirname,$file);
	    if ((!-e $dest_file) && (!-d $src_file))
	    {
		# just copy the original file back to the tmp directory
		copy($src_file,$dest_file) or die "Can't copy file $src_file to $dest_file $!";
	    }
	}
	
	# tidy the input file
	my $tidy_output_filename = $hdl_output_filename;
	if ($self->{'tidy_html'})
	{
	    $tidy_output_filename = &util::filename_cat($tmp_dirname, "$tailname$suffix");
	    $tidy_output_filename = $self->tmp_tidy_file($hdl_output_filename,$tidy_output_filename);
	}
	$tmp_filename = $tidy_output_filename;
    }
    else
    {
    	if (!-e $tmp_filename)
	{
	    # just copy the original file back to the tmp directory
	    copy($input_filename,$tmp_filename) or die "Can't copy file $input_filename to $tmp_filename $!";
	}
    }
    
    return $tmp_filename;
}


# Will make the html input file as a proper XML file with removed font tag and
# image size added to the img tag.
# The tidying process takes place in a collection specific 'tmp' directory so 
# that we don't accidentally damage the input.
sub tmp_tidy_file 
{
    my $self = shift (@_);
    my ($file,$cnfile) = @_;
    my $input_filename = $file;
    my $tmp_filename = $cnfile;
    
    # get the input filename
    my ($tailname, $dirname, $suffix) = &File::Basename::fileparse($input_filename, "\\.[^\\.]+\$");

    require HTML::TokeParser::Simple;
    
    # create HTML parser to decode the input file
    my $parser = HTML::TokeParser::Simple->new($input_filename);

    # write HTML tmp file without the font tag and image size are added to the img tag
    open (PROD, ">$tmp_filename") || die("Error Writing to File: $tmp_filename $!");
    while (my $token = $parser->get_token())
    {
	# is it an img tag
	if ($token->is_start_tag('img'))
	{
	    # get the attributes
	    my $attr = $token->return_attr;

	    # get the full path to the image
	    my $img_file = &util::filename_cat($dirname,$attr->{src});
	    
	    # set the width and height attribute
	    ($attr->{width}, $attr->{height}) = imgsize($img_file);

	    # recreate the tag
	    print PROD "<img";
	    print PROD map { qq { $_="$attr->{$_}"} } keys %$attr;
	    print PROD ">";
	}
	# is it a font tag
	else 
	{
	    if (($token->is_start_tag('font')) || ($token->is_end_tag('font')))
	    {
		# remove font tag
		print PROD "";
	    }
	    else
	    {
		# print without changes
		print PROD $token->as_is;
	    }
	}
    }
    close (PROD) || die("Error Closing File: $tmp_filename $!");

    # run html-tidy on the tmp file to make it a proper XML file
    my $tidyfile = `tidy -utf8 -wrap 0 -asxml $tmp_filename`;

    # write result back to the tmp file
    open (PROD, ">$tmp_filename") || die("Error Writing to File: $tmp_filename $!");
    print PROD $tidyfile;
    close (PROD) || die("Error Closing File: $tmp_filename $!");
    
    # return the output filename
    return $tmp_filename;
} 

sub read_into_doc_obj 
{
    my $self = shift (@_);  
    my ($pluginfo, $base_dir, $file, $block_hash, $metadata, $processor, $maxdocs, $total_count, $gli) = @_;
        
    # get the input file
    my $input_filename = $file;
    my ($tailname, $dirname, $suffix) = &File::Basename::fileparse($input_filename, "\\.[^\\.]+\$");
    $suffix = lc($suffix);   
    
    if (($self->{'tidy_html'}) || ($self->{'old_style_HDL'}))
    {
	# because the document has to be sectionalized set the description tags 
	$self->{'description_tags'} = 1;
	
	# set the file to be tidied
	$input_filename = &util::filename_cat($base_dir,$file) if $base_dir =~ m/\w/;
	
	# get the tidied file
	#my $tidy_filename = $self->tmp_tidy_file($input_filename);
	my $tidy_filename = $self->convert_tidy_or_oldHDL_file($input_filename);
	
	# derive tmp filename from input filename
	my ($tailname, $dirname, $suffix) = &File::Basename::fileparse($tidy_filename, "\\.[^\\.]+\$");
	
	# set the new input file and base_dir to be from the tidied file
	$file = "$tailname$suffix";
	$base_dir = $dirname;
    }
    
    # call the parent read_into_doc_obj
    my ($process_status,$doc_obj) = $self->SUPER::read_into_doc_obj($pluginfo, $base_dir, $file, $block_hash, $metadata, $processor, $maxdocs, $total_count, $gli);
    
    return ($process_status,$doc_obj);
}

sub new {
    my ($class) = shift (@_);
    my ($pluginlist,$inputargs,$hashArgOptLists) = @_;
    push(@$pluginlist, $class);
    
    push(@{$hashArgOptLists->{"ArgList"}},@{$arguments});
    push(@{$hashArgOptLists->{"OptList"}},$options);
    

    my $self = new ReadTextFile($pluginlist,$inputargs,$hashArgOptLists);
    
    if ($self->{'w3mir'}) {
	$self->{'file_is_url'} = 1;
    }
    $self->{'aux_files'} = {};
    $self->{'dir_num'} = 0;
    $self->{'file_num'} = 0;
    
    return bless $self, $class;
}

# may want to use (?i)\.(gif|jpe?g|jpe|png|css|js(?:@.*)?)$
# if have eg <script language="javascript" src="img/lib.js@123">
sub get_default_block_exp {
    my $self = shift (@_);
    
    #return q^(?i)\.(gif|jpe?g|jpe|jpg|png|css)$^;
    return "";
}

sub get_default_process_exp {
    my $self = shift (@_);
    
    # the last option is an attempt to encode the concept of an html query ...
    return q^(?i)(\.html?|\.shtml|\.shm|\.asp|\.php\d?|\.cgi|.+\?.+=.*)$^;
}

sub store_block_files
{
    my $self =shift (@_);
    my ($filename_full_path, $block_hash) = @_;

    my $html_fname = $filename_full_path;
    my @file_blocks;
    
    my ($language, $encoding) = $self->textcat_get_language_encoding ($filename_full_path);

    # read in file ($text will be in utf8)
    my $raw_text = "";
    $self->read_file_no_decoding ($filename_full_path, \$raw_text);

    my $textref = \$raw_text;
    my $opencom = '(?:<!--|&lt;!(?:&mdash;|&#151;|--))';
    my $closecom = '(?:-->|(?:&mdash;|&#151;|--)&gt;)';
    $$textref =~ s/$opencom(.*?)$closecom//gs;

    my $attval = "\\\"[^\\\"]+\\\"|[^\\s>]+";
    my @img_matches = ($$textref =~ m/<img[^>]*?src\s*=\s*($attval)[^>]*>/igs);
    my @usemap_matches = ($$textref =~ m/<img[^>]*?usemap\s*=\s*($attval)[^>]*>/igs);
    my @link_matches = ($$textref =~ m/<link[^>]*?href\s*=\s*($attval)[^>]*>/igs);
    my @embed_matches = ($$textref =~ m/<embed[^>]*?src\s*=\s*($attval)[^>]*>/igs);
    my @tabbg_matches = ($$textref =~ m/<(?:table|tr|td)[^>]*?background\s*=\s*($attval)[^>]*>/igs);
    my @script_matches = ($$textref =~ m/<script[^>]*?src\s*=\s*($attval)[^>]*>/igs);

    if(!defined $self->{'utf8_to_original_filename'}) { 
	# maps from utf8 converted link name -> original filename referrred to by (possibly URL-encoded) src url
	$self->{'utf8_to_original_filename'} = {};
    }

    foreach my $link (@img_matches, @usemap_matches, @link_matches, @embed_matches, @tabbg_matches, @script_matches) {

	# remove quotes from link at start and end if necessary
	if ($link=~/^\"/) {
	    $link=~s/^\"//;
	    $link=~s/\"$//;
	}

	$link =~ s/\#.*$//s; # remove any anchor names, e.g. foo.html#name becomes foo.html
	# some links may just be anchor names
	next unless ($link =~ /\S+/);

	if ($link !~ m@^/@ && $link !~ m/^([A-Z]:?)\\/) {
	    # Turn relative file path into full path
	    my $dirname = &File::Basename::dirname($filename_full_path);
	    $link = &util::filename_cat($dirname, $link);
	}
	$link = $self->eval_dir_dots($link);
	

	# this is the actual filename on the filesystem (that the link refers to)
	my $url_original_filename = $self->opt_url_decode($link);

	# Convert the url_original_filename into its utf8 version. Store the utf8 link along with the url_original_filename
	my $utf8_link = "";
	$self->decode_text($link,$encoding,$language,\$utf8_link);
###	my $utf8_url_encoded_link = &unicode::url_encode($utf8_link);

	$self->{'utf8_to_original_filename'}->{$utf8_link} = $url_original_filename;
###	$self->{'utf8_to_original_filename'}->{$utf8_url_encoded_link} = $url_original_filename;

#	print STDERR "**** Storing block link: $link\n";
#	print STDERR "**** URL original filename: $url_original_filename\n";
	print STDERR "**** utf8_encoded_link to original src filename:\n\t$utf8_link\n\t".$self->{'utf8_to_original_filename'}->{$utf8_link}."\n";

	$block_hash->{'file_blocks'}->{$url_original_filename} = 1;
    }
}

# Given a filename in any encoding, will URL decode it to get back the original filename
# in the original encoding. Because this method is intended to work out the *original* 
# filename*, it not URL decode any filename if a file by the name of the *URL-encoded*
# string already exists in the local folder.
# Return the original filename corresponding to the parameter URL-encoded filename, and
# a decoded flag that is set to true iff URL-decoding had to be applied.
sub opt_url_decode {
    my $self = shift (@_);
    my ($link) = @_;

    # Replace %XX's in URL with decoded value if required.
    # Note that the filename may include the %XX in some situations
    if ($link =~ m/\%[A-F0-9]{2}/i) {
	if (!-e $link) {
	    $link = &unicode::url_decode($link);
	}
    } 

    return $link;
}


# do plugin specific processing of doc_obj
sub process {
    my $self = shift (@_);
    my ($textref, $pluginfo, $base_dir, $file, $metadata, $doc_obj, $gli) = @_;
    my $outhandle = $self->{'outhandle'};

    if ($ENV{'GSDLOS'} =~ m/^windows/i) {
	# this makes life so much easier... perl can cope with unix-style '/'s.
	$base_dir =~ s@(\\)+@/@g;
	$file =~ s@(\\)+@/@g; 
    }
    
    # reset per-doc stuff...
    $self->{'aux_files'} = {};
    $self->{'dir_num'} = 0;
    $self->{'file_num'} = 0;

    # process an HTML file where sections are divided by headings tags (H1, H2 ...)
    # you can also include metadata in the format (X can be any number)
    # <hX>Title<!--gsdl-metadata
    #	<Metadata name="name1">value1</Metadata>
    #	...
    #	<Metadata name="nameN">valueN</Metadata>
    #--></hX>
    if ($self->{'sectionalise_using_h_tags'}) {
	# description_tags should allways be activated because we convert headings to description tags
	$self->{'description_tags'} = 1;

	my $arrSections = [];
	$$textref =~ s/<h([0-9]+)[^>]*>(.*?)<\/h[0-9]+>/$self->process_heading($1, $2, $arrSections, $file)/isge;

	if (scalar(@$arrSections)) {
	    my $strMetadata = $self->update_section_data($arrSections, -1);
	    if (length($strMetadata)) {
		$strMetadata = '<!--' . $strMetadata . "\n-->\n</body>";
		$$textref =~ s/<\/body>/$strMetadata/ig;
	    }
	}
    }

    my $cursection = $doc_obj->get_top_section();

    $self->extract_metadata ($textref, $metadata, $doc_obj, $cursection)
	unless $self->{'no_metadata'} || $self->{'description_tags'};

    # Store URL for page as metadata - this can be used for an
    # altavista style search interface. The URL won't be valid
    # unless the file structure contains the domain name (i.e.
    # like when w3mir is used to download a website).

    # URL metadata (even invalid ones) are used to support internal
    # links, so even if 'file_is_url' is off, still need to store info

#    print STDERR "#### file: $file\n";
    my ($tailname,$dirname,$suffix) = &File::Basename::fileparse($file, "\\.[^\\.]+\$");
    my $utf8_file = $self->filename_to_utf8_metadata($file);
#    $utf8_file = &unicode::url_encode($utf8_file);

    my $web_url = "http://";
    if(defined $dirname) { # local directory
	$web_url = $web_url.$dirname.$utf8_file; 
    } else {
	$web_url = $web_url.$utf8_file;
    }
#    print STDERR "#### weburl: $web_url\n";

    $doc_obj->add_utf8_metadata($cursection, "URL", $web_url);

    if ($self->{'file_is_url'}) {
	$doc_obj->add_metadata($cursection, "weblink", "<a href=\"$web_url\">");
	$doc_obj->add_metadata($cursection, "webicon", "_iconworld_");
	$doc_obj->add_metadata($cursection, "/weblink", "</a>");
    }

    if ($self->{'description_tags'}) {
	# remove the html header - note that doing this here means any
	# sections defined within the header will be lost (so all <Section>
	# tags must appear within the body of the HTML)
	my ($head_keep) = ($$textref =~ m/^(.*?)<body[^>]*>/is);

	$$textref =~ s/^.*?<body[^>]*>//is;
	$$textref =~ s/(<\/body[^>]*>|<\/html[^>]*>)//isg;

	my $opencom = '(?:<!--|&lt;!(?:&mdash;|&#151;|--))';
	my $closecom = '(?:-->|(?:&mdash;|&#151;|--)&gt;)';

	my $lt = '(?:<|&lt;)';
	my $gt = '(?:>|&gt;)';
	my $quot = '(?:"|&quot;|&rdquo;|&ldquo;)';

	my $dont_strip = '';
	if ($self->{'no_strip_metadata_html'}) {
	    ($dont_strip = $self->{'no_strip_metadata_html'}) =~ s{,}{|}g;
	}

	my $found_something = 0; my $top = 1;
	while ($$textref =~ s/^(.*?)$opencom(.*?)$closecom//s) {
	    my $text = $1;
	    my $comment = $2;
	    if (defined $text) {
		# text before a comment - note that getting to here
		# doesn't necessarily mean there are Section tags in
		# the document
		$self->process_section(\$text, $base_dir, $file, $doc_obj, $cursection);
	    }
	    while ($comment =~ s/$lt(.*?)$gt//s) {
		my $tag = $1;
		if ($tag eq "Section") {
		    $found_something = 1;
		    $cursection = $doc_obj->insert_section($doc_obj->get_end_child($cursection)) unless $top;
		    $top = 0;
		} elsif ($tag eq "/Section") {
		    $found_something = 1;
		    $cursection = $doc_obj->get_parent_section ($cursection);
		} elsif ($tag =~ m/^Metadata name=$quot(.*?)$quot/s) {
		    my $metaname = $1;
		    my $accumulate = $tag =~ m/mode=${quot}accumulate${quot}/ ? 1 : 0;
		    $comment =~ s/^(.*?)$lt\/Metadata$gt//s;
		    my $metavalue = $1;
		    $metavalue =~ s/^\s+//;
		    $metavalue =~ s/\s+$//;
                    # assume that no metadata value intentionally includes
                    # carriage returns or HTML tags (if they're there they
                    # were probably introduced when converting to HTML from
                    # some other format).
		    # actually some people want to have html tags in their
		    # metadata.
		    $metavalue =~ s/[\cJ\cM]/ /sg;
		    $metavalue =~ s/<[^>]+>//sg
			unless $dont_strip && ($dont_strip eq 'all' || $metaname =~ m/^($dont_strip)$/);
		    $metavalue =~ s/\s+/ /sg;
		    if ($accumulate) {
			$doc_obj->add_utf8_metadata($cursection, $metaname, $metavalue);
		    } else {
			$doc_obj->set_utf8_metadata_element($cursection, $metaname, $metavalue);	
		    }
		} elsif ($tag eq "Description" || $tag eq "/Description") {
		    # do nothing with containing Description tags
		} else {
		    # simple HTML tag (probably created by the conversion
		    # to HTML from some other format) - we'll ignore it and
		    # hope for the best ;-)
		}
	    }
	}
	if ($cursection ne "") {
	    print $outhandle "HTMLPlugin: WARNING: $file contains unmatched <Section></Section> tags\n";
	}

	$$textref =~ s/^.*?<body[^>]*>//is;
	$$textref =~ s/(<\/body[^>]*>|<\/html[^>]*>)//isg;
	if ($$textref =~ m/\S/) {
	    if (!$found_something) {
		if ($self->{'verbosity'} > 2) {
		    print $outhandle "HTMLPlugin: WARNING: $file appears to contain no Section tags so\n";
		    print $outhandle "          will be processed as a single section document\n";
		}

		# go ahead and process single-section document
		$self->process_section($textref, $base_dir, $file, $doc_obj, $cursection);

		# if document contains no Section tags we'll go ahead
		# and extract metadata (this won't have been done
		# above as the -description_tags option prevents it)
		my $complete_text = $head_keep.$doc_obj->get_text($cursection);
		$self->extract_metadata (\$complete_text, $metadata, $doc_obj, $cursection) 
		    unless $self->{'no_metadata'};

	    } else {
		print $outhandle "HTMLPlugin: WARNING: $file contains the following text outside\n";
		print $outhandle "          of the final closing </Section> tag. This text will\n";
		print $outhandle "          be ignored.";

		my ($text);
		if (length($$textref) > 30) {
		    $text = substr($$textref, 0, 30) . "...";
		} else {
		    $text = $$textref;
		}
		$text =~ s/\n/ /isg;
		print $outhandle " ($text)\n";
	    }
	} elsif (!$found_something) {

	    if ($self->{'verbosity'} > 2) {
		# may get to here if document contained no valid Section
		# tags but did contain some comments. The text will have
		# been processed already but we should print the warning
		# as above and extract metadata
		print $outhandle "HTMLPlugin: WARNING: $file appears to contain no Section tags and\n";
		print $outhandle "          is blank or empty.  Metadata will be assigned if present.\n";
	    }

	    my $complete_text = $head_keep.$doc_obj->get_text($cursection);
	    $self->extract_metadata (\$complete_text, $metadata, $doc_obj, $cursection) 
		unless $self->{'no_metadata'};
	}
	
    } else {

	# remove header and footer
	if (!$self->{'keep_head'} || $self->{'description_tags'}) {
	    $$textref =~ s/^.*?<body[^>]*>//is;
	    $$textref =~ s/(<\/body[^>]*>|<\/html[^>]*>)//isg;
	}

	# single section document
	$self->process_section($textref, $base_dir, $file, $doc_obj, $cursection);
    }
    return 1;
}


sub process_heading
{
    my ($self, $nHeadNo, $strHeadingText, $arrSections, $file) = @_;
    $strHeadingText = '' if (!defined($strHeadingText));

    my $strMetadata = $self->update_section_data($arrSections, int($nHeadNo));

    my $strSecMetadata = '';
    while ($strHeadingText =~ s/<!--gsdl-metadata(.*?)-->//is)
    {
	$strSecMetadata .= $1;
    }

    $strHeadingText =~ s/^\s+//g;
    $strHeadingText =~ s/\s+$//g;
    $strSecMetadata =~ s/^\s+//g;
    $strSecMetadata =~ s/\s+$//g;

    $strMetadata .= "\n<Section>\n\t<Description>\n\t\t<Metadata name=\"Title\">" . $strHeadingText . "</Metadata>\n";

    if (length($strSecMetadata)) {
	$strMetadata .= "\t\t" . $strSecMetadata . "\n";
    }

    $strMetadata .= "\t</Description>\n";

    return "<!--" . $strMetadata . "-->";
}


sub update_section_data
{
    my ($self, $arrSections, $nCurTocNo) = @_;
    my ($strBuffer, $nLast, $nSections) = ('', 0, scalar(@$arrSections));

    if ($nSections == 0) {
	push @$arrSections, $nCurTocNo;
	return $strBuffer;
    }
    $nLast = $arrSections->[$nSections - 1];
    if ($nCurTocNo > $nLast) {
	push @$arrSections, $nCurTocNo;
	return $strBuffer;
    }
    for(my $i = $nSections - 1; $i >= 0; $i--) {
	if ($nCurTocNo <= $arrSections->[$i]) {
	    $strBuffer .= "\n</Section>";
	    pop @$arrSections;
	}
    }
    push @$arrSections, $nCurTocNo;
    return $strBuffer;
}


# note that process_section may be called multiple times for a single
# section (relying on the fact that add_utf8_text appends the text to any
# that may exist already).
sub process_section {
    my $self = shift (@_);
    my ($textref, $base_dir, $file, $doc_obj, $cursection) = @_;
    # trap links
    if (!$self->{'nolinks'}) {
	# usemap="./#index" not handled correctly => change to "#index"
##	$$textref =~ s/(<img[^>]*?usemap\s*=\s*[\"\']?)([^\"\'>\s]+)([\"\']?[^>]*>)/

	$$textref =~ s/(<img[^>]*?usemap\s*=\s*)((?:[\"][^\"]+[\"])|(?:[\'][^\']+[\'])|(?:[^\s\/>]+))([^>]*>)/
	    $self->replace_usemap_links($1, $2, $3)/isge;

##	$$textref =~ s/(<(?:a|area|frame|link|script)\s+[^>]*?\s*(?:href|src)\s*=\s*[\"\']?)([^\"\'>\s]+)([\"\']?[^>]*>)/

	$$textref =~ s/(<(?:a|area|frame|link|script)\s+[^>]*?\s*(?:href|src)\s*=\s*)((?:[\"][^\"]+[\"])|(?:[\'][^\']+[\'])|(?:[^\s\/>]+))([^>]*>)/
	    $self->replace_href_links ($1, $2, $3, $base_dir, $file, $doc_obj, $cursection)/isge;
    }

    # trap images

    # Previously, by default, HTMLPlugin would embed <img> tags inside anchor tags
    # i.e. <a href="image><img src="image"></a> in order to overcome a problem that
    # turned regular text succeeding images into links. That is, by embedding <imgs>
    # inside <a href=""></a>, the text following images were no longer misbehaving.
    # However, there would be many occasions whereby images were not meant to link
    # to their source images but where the images would link to another web page.
    # To allow this, the no_image_links option was introduced: it would prevent
    # the behaviour of embedding images into links that referenced the source images.

    # Somewhere along the line, the problem of normal text turning into links when 
    # such text followed images which were not embedded in <a href=""></a> ceased 
    # to occur. This is why the following lines have been commented out (as well as 
    # two lines in replace_images). They appear to no longer apply.

    # If at any time, there is a need for having images embedded in <a> anchor tags,
    # then it might be better to turn that into an HTMLPlugin option rather than make
    # it the default behaviour. Also, eventually, no_image_links needs to become
    # a deprecated option for HTMLPlugin as it has now become the default behaviour.

    #if(!$self->{'no_image_links'}){
    $$textref =~ s/(<(?:img|embed|table|tr|td)[^>]*?(?:src|background)\s*=\s*)((?:[\"][^\"]+[\"])|(?:[\'][^\']+[\'])|(?:[^\s\/>]+))([^>]*>)/
	$self->replace_images ($1, $2, $3, $base_dir, $file, $doc_obj, $cursection)/isge;
    #}

    # add text to document object
    # turn \ into \\ so that the rest of greenstone doesn't think there
    # is an escape code following. (Macro parsing loses them...)
    $$textref =~ s/\\/\\\\/go;
    
    $doc_obj->add_utf8_text($cursection, $$textref);
}

sub replace_images {
    my $self = shift (@_);
    my ($front, $link, $back, $base_dir, 
	$file, $doc_obj, $section) = @_;

    # remove quotes from link at start and end if necessary
    if ($link=~/^[\"\']/) {
	$link=~s/^[\"\']//;
	$link=~s/[\"\']$//;
	$front.='"';
	$back="\"$back";
    }

    $link =~ s/\n/ /g;

    # Hack to overcome Windows wv 0.7.1 bug that causes embedded images to be broken
    # If the Word file path has spaces in it, wv messes up and you end up with
    #   absolute paths for the images, and without the "file://" prefix
    # So check for this special case and massage the data to be correct
    if ($ENV{'GSDLOS'} =~ m/^windows/i && $self->{'plugin_type'} eq "WordPlug" && $link =~ m/^[A-Za-z]\:\\/) {
	$link =~ s/^.*\\([^\\]+)$/$1/;
    }
    
    my ($href, $hash_part, $rl) = $self->format_link ($link, $base_dir, $file);

    my $img_file =  $self->add_file ($href, $rl, $hash_part, $base_dir, $doc_obj, $section);

#    print STDERR "**** link = $link\n";
#    print STDERR "**** href = $href\n";
#    print STDERR "**** img_file = $img_file\n";

    my $anchor_name = $img_file;
    #$anchor_name =~ s/^.*\///;
    #$anchor_name = "<a name=\"$anchor_name\" ></a>";

    my $image_link = $front . $img_file .$back;
    return $image_link;

    # The reasons for why the following two lines are no longer necessary can be 
    # found in subroutine process_section
    #my $anchor_link = "<a href=\"$img_file\" >".$image_link."</a>";  
    #return $anchor_link;	
    
    #return $front . $img_file . $back . $anchor_name;
}

sub replace_href_links {
    my $self = shift (@_);
    my ($front, $link, $back, $base_dir, $file, $doc_obj, $section) = @_;

    # remove quotes from link at start and end if necessary
    if ($link=~/^[\"\']/) {
	$link=~s/^[\"\']//;
	$link=~s/[\"\']$//;
	$front.='"';
	$back="\"$back";
    }

    # attempt to sort out targets - frames are not handled 
    # well in this plugin and some cases will screw things
    # up - e.g. the _parent target (so we'll just remove 
    # them all ;-)
    $front =~ s/(target=\"?)_top(\"?)/$1_gsdltop_$2/is;
    $back =~ s/(target=\"?)_top(\"?)/$1_gsdltop_$2/is;
    $front =~ s/target=\"?_parent\"?//is;
    $back =~ s/target=\"?_parent\"?//is;

    return $front . $link . $back if $link =~ m/^\#/s;
    $link =~ s/\n/ /g;

    # Find file referred to by $link on file system 
    # This is more complicated than it sounds when char encodings
    # is taken in to account
##    &unicode::ensure_utf8(\$link);
##    $link = &unicode::url_encode($link);
#    print STDERR "#### filepath: ".&util::filename_cat($base_dir,$file)."\n";
#    print STDERR "#### link: $link\n";

    my ($href, $hash_part, $rl) = $self->format_link ($link, $base_dir, $file);
#    print STDERR "#### href: $href\n";
 
    # href may use '\'s where '/'s should be on Windows
    $href =~ s/\\/\//g;

##    $href = &unicode::url_decode($href);
#    print STDERR "#### href again: $href\n";
    my ($filename) = $href =~ m/^(?:.*?):(?:\/\/)?(.*)/;
    

    ##### leave all these links alone (they won't be picked up by intermediate 
    ##### pages). I think that's safest when dealing with frames, targets etc.
    ##### (at least until I think of a better way to do it). Problems occur with
    ##### mailto links from within small frames, the intermediate page is displayed
    ##### within that frame and can't be seen. There is still potential for this to
    ##### happen even with html pages - the solution seems to be to somehow tell
    ##### the browser from the server side to display the page being sent (i.e. 
    ##### the intermediate page) in the top level window - I'm not sure if that's 
    ##### possible - the following line should probably be deleted if that can be done
    return $front . $link . $back if $href =~ m/^(mailto|news|gopher|nntp|telnet|javascript):/is;


    if (($rl == 0) || ($filename =~ m/$self->{'process_exp'}/) || 
	($href =~ m/\/$/) || ($href =~ m/^(mailto|news|gopher|nntp|telnet|javascript):/i)) {
	&ghtml::urlsafe ($href);
	return $front . "_httpextlink_&rl=" . $rl . "&href=" . $href . $hash_part . $back;
    } else {
	# link is to some other type of file (eg image) so we'll
	# need to associate that file
	return $front . $self->add_file ($href, $rl, $hash_part, $base_dir, $doc_obj, $section) . $back;
    }
}

sub add_file {
    my $self = shift (@_);
    my ($href, $rl, $hash_part, $base_dir, $doc_obj, $section) = @_;
    my ($newname);

    my $filename = $href;
    if ($base_dir eq "") {
	# remove http:/ thereby leaving one slash at the start
	$filename =~ s/^[^:]*:\///;
    }
    else {
	# remove http://
	$filename =~ s/^[^:]*:\/\///;
    }

    $filename = &util::filename_cat($base_dir, $filename);
#    print STDERR "**** filename: $filename\n";
    # Replace %XX's in URL with decoded value if required. Note that the filename may include the %XX in some
    # situations. If the *original* file's name was in URL encoding, the following method will not decode it.
    my $utf8_filename = $filename;
    
#    print STDERR "*** filename before URL decoding: $filename\n";
    $filename = $self->opt_url_decode($utf8_filename);
#    print STDERR "*** filename after URL decoding:  $filename\n\n";

    # some special processing if the intended filename was converted to utf8, but
    # the actual file still needs to be renamed
    if (!-e $filename) {
	# try the original filename stored in map
	my $original_filename = $self->{'utf8_to_original_filename'}->{$filename};
	if (-e $original_filename) {
	    $filename = $original_filename;
	}
    }
    
    my ($ext) = $filename =~ m/(\.[^\.]*)$/;

    if ($rl == 0) {
	if ((!defined $ext) || ($ext !~ m/$self->{'assoc_files'}/)) {
	    return "_httpextlink_&rl=0&el=prompt&href=" . $href . $hash_part;
	}
	else {
	    return "_httpextlink_&rl=0&el=direct&href=" . $href . $hash_part;
	}
    }

    if ((!defined $ext) || ($ext !~ m/$self->{'assoc_files'}/)) {
	return "_httpextlink_&rl=" . $rl . "&href=" . $href . $hash_part;
    }
    if ($self->{'rename_assoc_files'}) {
	if (defined $self->{'aux_files'}->{$href}) {
	    $newname = $self->{'aux_files'}->{$href}->{'dir_num'} . "/" .
		$self->{'aux_files'}->{$href}->{'file_num'} . $ext;
	} else {
	    $newname = $self->{'dir_num'} . "/" . $self->{'file_num'} . $ext;
	    $self->{'aux_files'}->{$href} = {'dir_num' => $self->{'dir_num'}, 'file_num' => $self->{'file_num'}};
	    $self->inc_filecount ();
	}
	$doc_obj->associate_file($filename, $newname, undef, $section);
	return "_httpdocimg_/$newname";
    } else {
	($newname) = $utf8_filename =~ m/([^\/\\]*)$/;
	
#	print STDERR "Before url encoding newname: $newname\n";
	# Make sure this name uses only ASCII characters 
	# => use URL encoding, as it preserves original encoding
	$newname = &unicode::url_encode($newname);
#	print STDERR "After url encoding newname: $newname\n";
#	print STDERR "*** Real name and converted filename:\n\t$filename\n\t$newname\n";

	$doc_obj->associate_file($filename, $newname, undef, $section);

	# Since the generated image will be URL-encoded to avoid file-system/browser mess-ups
	# of filenames, URL-encode the additional percent signs of the URL-encoded filename
	my $newname_url = $newname;
	$newname_url =~ s/%/%25/g;
	return "_httpdocimg_/$newname_url";	
    }
}


sub format_link {
    my $self = shift (@_);
    my ($link, $base_dir, $file) = @_;

    my ($before_hash, $hash_part) = $link =~ m/^([^\#]*)(\#?.*)$/;
    
    $hash_part = "" if !defined $hash_part;
    if (!defined $before_hash || $before_hash !~ m/[\w\.\/]/) {
	my $outhandle = $self->{'outhandle'};
	print $outhandle "HTMLPlugin: ERROR - badly formatted tag ignored ($link)\n"
	    if $self->{'verbosity'};
	return ($link, "", 0);
    }

    if ($before_hash =~ s@^((?:http|ftp|file)://)@@i) {
	my $type = $1;

	if ($link =~ m/^(http|ftp):/i) {
	    # Turn url (using /) into file name (possibly using \ on windows)
	    my @http_dir_split = split('/', $before_hash);
	    $before_hash = &util::filename_cat(@http_dir_split);
	}

	$before_hash = $self->eval_dir_dots($before_hash);
	
	my $linkfilename = &util::filename_cat ($base_dir, $before_hash);
	
	my $rl = 0;
	$rl = 1 if (-e $linkfilename);

	# make sure there's a slash on the end if it's a directory
	if ($before_hash !~ m/\/$/) {
	    $before_hash .= "/" if (-d $linkfilename);
	}
	return ($type . $before_hash, $hash_part, $rl);
	
    } elsif ($link !~ m/^(mailto|news|gopher|nntp|telnet|javascript):/i && $link !~ m/^\//) {

	if ($before_hash =~ s@^/@@ || $before_hash =~ m/\\/) {

	    # the first directory will be the domain name if file_is_url
	    # to generate archives, otherwise we'll assume all files are
	    # from the same site and base_dir is the root

	    if ($self->{'file_is_url'}) {
		my @dirs = split /[\/\\]/, $file;
		my $domname = shift (@dirs);
		$before_hash = &util::filename_cat($domname, $before_hash);
		$before_hash =~ s@\\@/@g; # for windows
	    }
	    else
	    {
		# see if link shares directory with source document
		# => turn into relative link if this is so!
		
		if ($ENV{'GSDLOS'} =~ m/^windows/i) {
		    # too difficult doing a pattern match with embedded '\'s...
		    my $win_before_hash=$before_hash;
		    $win_before_hash =~ s@(\\)+@/@g;
		    # $base_dir is already similarly "converted" on windows.
		    if ($win_before_hash =~ s@^$base_dir/@@o) {
			# if this is true, we removed a prefix
			$before_hash=$win_before_hash;
		    }
		}
		else {
		    # before_hash has lost leading slash by this point,
		    # -> add back in prior to substitution with $base_dir
		    $before_hash = "/$before_hash"; 

		    $before_hash = &util::filename_cat("",$before_hash);
		    $before_hash =~ s@^$base_dir/@@;
		}
	    }
	} else {
	    # Turn relative file path into full path
	    my $dirname = &File::Basename::dirname($file);
	    $before_hash = &util::filename_cat($dirname, $before_hash);
	    $before_hash = $self->eval_dir_dots($before_hash);	    	    
	    
#	    print STDERR "#### before_hash: $before_hash\n";
	}

	my $linkfilename = &util::filename_cat ($base_dir, $before_hash); 
	# make sure there's a slash on the end if it's a directory
	if ($before_hash !~ m/\/$/) {
	    $before_hash .= "/" if (-d $linkfilename);
	}
	return ("http://" . $before_hash, $hash_part, 1);
    } else {
	# mailto, news, nntp, telnet, javascript or gopher link
	return ($before_hash, "", 0);
    }
}

sub extract_first_NNNN_characters {
    my $self = shift (@_);
    my ($textref, $doc_obj, $thissection) = @_;
    
    foreach my $size (split /,/, $self->{'first'}) {
	my $tmptext =  $$textref;
	# skip to the body
	$tmptext =~ s/.*<body[^>]*>//i;
	# remove javascript
	$tmptext =~ s@<script.*?</script>@ @sig;
	$tmptext =~ s/<[^>]*>/ /g;
	$tmptext =~ s/&nbsp;/ /g;
	$tmptext =~ s/^\s+//;
	$tmptext =~ s/\s+$//;
	$tmptext =~ s/\s+/ /gs;
	$tmptext = &unicode::substr ($tmptext, 0, $size);
	$tmptext =~ s/\s\S*$/&#8230;/; # adds an ellipse (...)
	$doc_obj->add_utf8_metadata ($thissection, "First$size", $tmptext);
    }
}


sub extract_metadata {
    my $self = shift (@_);
    my ($textref, $metadata, $doc_obj, $section) = @_;
    my $outhandle = $self->{'outhandle'};
    # if we don't want metadata, we may as well not be here ...
    return if (!defined $self->{'metadata_fields'});

    # metadata fields to extract/save. 'key' is the (lowercase) name of the
    # html meta, 'value' is the metadata name for greenstone to use
    my %find_fields = ();

    my %creator_fields = (); # short-cut for lookups


    foreach my $field (split /,/, $self->{'metadata_fields'}) {
        $field =~ s/^\s+//; # remove leading whitespace
        $field =~ s/\s+$//; # remove trailing whitespace

	# support tag<tagname>
	if ($field =~ m/^(.*?)<(.*?)>$/) {
	    # "$2" is the user's preferred gs metadata name
	    $find_fields{lc($1)}=$2; # lc = lowercase
	} else { # no <tagname> for mapping
	    # "$field" is the user's preferred gs metadata name
	    $find_fields{lc($field)}=$field; # lc = lowercase
	}
    }

    if (defined $self->{'hunt_creator_metadata'} &&
	$self->{'hunt_creator_metadata'} == 1 ) {
	my @extra_fields =
	    (
	     'author',
	     'author.email',
	     'creator',
	     'dc.creator',
	     'dc.creator.corporatename',
	     );

	# add the creator_metadata fields to search for
	foreach my $field (@extra_fields) {
	    $creator_fields{$field}=0; # add to lookup hash
	}
    }


    # find the header in the html file, which has the meta tags
    $$textref =~ m@<head>(.*?)</head>@si;

    my $html_header=$1;

    # go through every <meta... tag defined in the html and see if it is
    # one of the tags we want to match.
    
    # special case for title - we want to remember if its been found
    my $found_title = 0;
    # this assumes that ">" won't appear. (I don't think it's allowed to...)
    $html_header =~ m/^/; # match the start of the string, for \G assertion
    
    while ($html_header =~ m/\G.*?<meta(.*?)>/sig) {
	my $metatag=$1;
	my ($tag, $value);

	# find the tag name
	$metatag =~ m/(?:name|http-equiv)\s*=\s*([\"\'])?(.*?)\1/is;
	$tag=$2;
	# in case they're not using " or ', but they should...
	if (! $tag) {
	    $metatag =~ m/(?:name|http-equiv)\s*=\s*([^\s\>]+)/is;
	    $tag=$1;
	}

	if (!defined $tag) {
	    print $outhandle "HTMLPlugin: can't find NAME in \"$metatag\"\n";
	    next;
	}
	
	# don't need to assign this field if it was passed in from a previous 
	# (recursive) plugin
	if (defined $metadata->{$tag}) {next}

	# find the tag content
	$metatag =~ m/content\s*=\s*([\"\'])?(.*?)\1/is;
	$value=$2;

	if (! $value) {
	    $metatag =~ m/(?:name|http-equiv)\s*=\s*([^\s\>]+)/is;
	    $value=$1;
	}
	if (!defined $value) {
	    print $outhandle "HTMLPlugin: can't find VALUE in \"$metatag\"\n";
	    next;
	}

	# clean up and add
	$value =~ s/\s+/ /gs;
	chomp($value); # remove trailing \n, if any
	if (exists $creator_fields{lc($tag)}) {
	    # map this value onto greenstone's "Creator" metadata
	    $tag='Creator';
	} elsif (!exists $find_fields{lc($tag)}) {
	    next; # don't want this tag
	} else {
	    # get the user's preferred capitalisation
	    $tag = $find_fields{lc($tag)};
	}
	if (lc($tag) eq "title") {
	    $found_title = 1;
	}
	print $outhandle " extracted \"$tag\" metadata \"$value\"\n" 
	    if ($self->{'verbosity'} > 2);
	if ($tag =~ m/date.*/i){
	    $tag = lc($tag);
	}
	$doc_obj->add_utf8_metadata($section, $tag, $value);

    }
    
    # TITLE: extract the document title
    if (exists $find_fields{'title'} && !$found_title) {
	# we want a title, and didn't find one in the meta tags
	# see if there's a <title> tag
	my $title;
	my $from = ""; # for debugging output only
	if ($html_header =~ m/<title[^>]*>([^<]+)<\/title[^>]*>/is) {
	    $title = $1;
	    $from = "<title> tags";
	}

	if (!defined $title) {
	    $from = "first 100 chars";
	    # if no title use first 100 or so characters
	    $title = $$textref;
	    $title =~ s/^\xFE\xFF//; # Remove unicode byte order mark	    
	    $title =~ s/^.*?<body>//si;
	    # ignore javascript!
	    $title =~ s@<script.*?</script>@ @sig;
	    $title =~ s/<\/([^>]+)><\1>//g; # (eg) </b><b> - no space
	    $title =~ s/<[^>]*>/ /g; # remove all HTML tags
	    $title = substr ($title, 0, 100);
	    $title =~ s/\s\S*$/.../;
	}
	$title =~ s/<[^>]*>/ /g; # remove html tags
	$title =~ s/&nbsp;/ /g;
	$title =~ s/(?:&nbsp;|\xc2\xa0)/ /g; # utf-8 for nbsp...
	$title =~ s/\s+/ /gs; # collapse multiple spaces
	$title =~ s/^\s*//;   # remove leading spaces
	$title =~ s/\s*$//;   # remove trailing spaces

	$title =~ s/^$self->{'title_sub'}// if ($self->{'title_sub'});
	$title =~ s/^\s+//s; # in case title_sub introduced any...
	$doc_obj->add_utf8_metadata ($section, 'Title', $title);
	print $outhandle " extracted Title metadata \"$title\" from $from\n" 
	    if ($self->{'verbosity'} > 2);
    } 
    
    # add FileFormat metadata
    $doc_obj->add_metadata($section,"FileFormat", "HTML");

    # Special, for metadata names such as tagH1 - extracts
    # the text between the first <H1> and </H1> tags into "H1" metadata.

    foreach my $field (keys %find_fields) {
	if ($field !~ m/^tag([a-z0-9]+)$/i) {next}
	my $tag = $1;
	if ($$textref =~ m@<$tag[^>]*>(.*?)</$tag[^>]*>@g) {
	    my $content = $1;
	    $content =~ s/&nbsp;/ /g;
	    $content =~ s/<[^>]*>/ /g;
	    $content =~ s/^\s+//;
	    $content =~ s/\s+$//;
	    $content =~ s/\s+/ /gs;
	    if ($content) {
		$tag=$find_fields{"tag$tag"}; # get the user's capitalisation
		$tag =~ s/^tag//i;
		$doc_obj->add_utf8_metadata ($section, $tag, $content);
		print $outhandle " extracted \"$tag\" metadata \"$content\"\n" 
		    if ($self->{'verbosity'} > 2);
	    }
	}
    }    
}


# evaluate any "../" to next directory up
# evaluate any "./" as here
sub eval_dir_dots {
    my $self = shift (@_);
    my ($filename) = @_;
    my $dirsep_os = &util::get_os_dirsep();
    my @dirsep = split(/$dirsep_os/,$filename);

    my @eval_dirs = ();
    foreach my $d (@dirsep) {
	if ($d eq "..") {
	    pop(@eval_dirs);
	    
	} elsif ($d eq ".") {
	    # do nothing!

	} else {
	    push(@eval_dirs,$d);
	}
    }

    # Need to fiddle with number of elements in @eval_dirs if the
    # first one is the empty string.  This is because of a
    # modification to util::filename_cat that supresses the addition
    # of a leading '/' character (or \ if windows) (intended to help
    # filename cat with relative paths) if the first entry in the
    # array is the empty string.  Making the array start with *two*
    # empty strings is a way to defeat this "smart" option.
    #
    if (scalar(@eval_dirs) > 0) {
	if ($eval_dirs[0] eq ""){
	    unshift(@eval_dirs,"");
	}
    }
    return &util::filename_cat(@eval_dirs);
}

sub replace_usemap_links {
    my $self = shift (@_);
    my ($front, $link, $back) = @_;

    # remove quotes from link at start and end if necessary
    if ($link=~/^[\"\']/) {
	$link=~s/^[\"\']//;
	$link=~s/[\"\']$//;
	$front.='"';
	$back="\"$back";
    }

    $link =~ s/^\.\///;
    return $front . $link . $back;
}

sub inc_filecount {
    my $self = shift (@_);

    if ($self->{'file_num'} == 1000) {
	$self->{'dir_num'} ++;
	$self->{'file_num'} = 0;
    } else {
	$self->{'file_num'} ++;
    }
}


# Extend read_file so that strings like &eacute; are
# converted to UTF8 internally.  
#
# We don't convert &lt; or &gt; or &amp; or &quot; in case
# they interfere with the GML files

sub read_file {
    my $self = shift(@_);
    my ($filename, $encoding, $language, $textref) = @_;

    $self->SUPER::read_file($filename, $encoding, $language, $textref);

    # Convert entities to their UTF8 equivalents
    $$textref =~ s/&(lt|gt|amp|quot|nbsp);/&z$1;/go;
    $$textref =~ s/&([^;]+);/&ghtml::getcharequiv($1,1)/gseo;
    $$textref =~ s/&z(lt|gt|amp|quot|nbsp);/&$1;/go;
}

1;
