package KITTENWEB::REPORT;

sub report_expandword { # orig word
    my($repword) = @_;
    $repword =~ s/([a-zA-Z])([A-Z][a-z])/$1 $2/g;
    $repword =~ s/([a-z])([A-Z])/$1 $2/g;
    return $repword;
}

sub report_replaceword { # word found
    my($db,$word) = @_;
    my $repword = &report_expandword($word);
    my (%ldb,%pdb);
    tie %ldb, STASH, $db, "link";
    return qq{<a href=$ldb{$word}>$repword</a>} if exists $ldb{$word};
    untie %ldb;
    tie %pdb, STASH, $db, "page";
    return qq{<a href="#$word">$repword</a>} if exists $pdb{$word};
    return qq{$repword};
}


# external
sub dumpreport { # database, tag
    # dump to stdout to avoid eating lots of memory
    my($db,$top) = @_;
    my (@pages, $thispage, @pageseen, @refs, %tmprefs, $onepage, $reppage);
    @pages = ($top);
    my %pdb;
    tie %pdb, STASH, $db, "page";
    &HTML::print_head("Project Notebook for $top");

    do {
	$thispage = shift @pages;
	push(@pageseen,$thispage);
	@refs = &KITTENWEB::RENDER::getrefs($pdb{$thispage});
	undef %tmprefs;
	grep($tmprefs{$_}=1,@refs);
	grep(undef $tmprefs{$_},@pages);
	grep(undef $tmprefs{$_},@pageseen);
	push(@pages, grep(defined($tmprefs{$_}), @refs));
#	     && exists $pdb{$_}
	if (exists $pdb{$thispage}) {
	    $reppage = &report_expandword($thispage);

	    print qq{
<a name="$thispage">
<h2>$reppage</h2>
};
	    $onepage =  &KITTENWEB::RENDER::renderhtml($pdb{$thispage});
	    $onepage =~ s#$KITTENWEB::RENDER::WikiWord#&report_replaceword($database,$1)#ge;
	    print $onepage;
	} else {
#	print "\t$thispage\n";
	}
    } while ($#pages >= 0);
    print $HTML::tail;
    untie %pdb;
}

1;
