sub loadAnchors() {
	local($db) = "anchor.txt";
	open(DB, $db) || die "$db: $!";
	while (<DB>) {
		chomp;
		next unless /\t/;
		$name = $`;
		$where = $';
		if (defined $ANCHOR{$name}) {
			$ANCHOR{$name} .= "\t$where";
		} else {
			$ANCHOR{$name} = $where;
		}
	}
	close DB;
}

sub checklink($$$) {
	local($url, $fragment, $foundat) = @_;
	$url =~ s|^\./||;
	# quick check
	return () if ($ANCHOR{$fragment} eq $url); 
	local(@locations) = split(/\t/, $ANCHOR{$fragment});
	foreach $location (@locations) {
		return () if ($location eq $url);
	}
#	print "$url#$fragment in $foundat not found. possibly in (",
#	$ANCHOR{$fragment}, ")\n";
	return @locations;
}

sub check($) {
	local($filename) = @_;
	local($error) = local($fixed) = 0;
	local($tmpfile) = $filename;
	$tmpfile =~ s/html$/new/;
	open(INPUT, $filename) || die "$filename: $!"; 
	open(OUTPUT, ">$tmpfile") || die "$tmpfile: $!";
	while (<INPUT>) {
		#quick check
		unless (/href=.*#/i) {
			print OUTPUT $_;
			next;
		}
		local(@links) = split(/<[Aa]/);
		local($index) = -1;
		foreach $link (@links) {
			$index++;
			next unless $link =~ /href=["']([^"'#]*)#([^"']*)["']/i;
			$url = $1;
			if ($url eq "") {
				$links[$index] =~ s/#/$filename#/;
				$url = $filename;
			}
			$fragment = $2;
			@list = &checklink($url, $fragment, $filename);
			if (@list == 0) {
				next;
			} elsif (@list == 1) {
				$links[$index] =~ s/$url/$list[0]/;
print "$filename: $url -> $list[0] for fragment #$fragment\n";
				$fixed++;
			} else {
				$links[$index] =~ s/$url/non.html/;
print "$filename: $url not found for fragment #$fragment\n";
				$error++;
			}
		}
		print OUTPUT join('<a', @links);
	}
	close(INPUT);
	close(OUTPUT);
	if (($error == 0) and ($fixed == 0)) {
		unlink $tmpfile;
	}
}

&loadAnchors();

if (@ARGV > 0) {
	@files = @ARGV;
} else {
	opendir(DIR, ".");
	@files = grep(/\.html$/, readdir(DIR));
	closedir(DIR);
}

foreach $file (@files) {
	&check($file);
}

if (@ARGV == 0) {
	print "hit enter to exit\n";
	scalar <STDIN>;
}
