package MKDoc::Registry;
use File::Temp qw /tempfile/;
use Apache::RegistryNG;
use Apache;
use strict;
use vars qw /@ISA/;
@ISA = qw /Apache::RegistryNG/;


sub handler
{
    my ($class, $r);
    if (@_ >= 2) {
        ($class, $r) = (shift, shift);
    }
    else {
        ($class, $r) = (__PACKAGE__, shift);
    }
    
    # if this request is not HEAD, then no problem
    return $r->SUPER::handler (@_) unless ($r->header_only);
    
    # otherwise we need to worry a little bit...
    
    # create a new temp file to store the data in
    my ($fh, $filename) = tempfile;
    my $headers = "";
    
    # saves STDOUT which we are going to redirect
    # non-obvious syntax, see perldoc -f open
    open (OLDOUT, ">&STDOUT");
    
    # prints STDOUT to /tmp/foo.out
    open (STDOUT, '>', $filename) || die "Can't redirect stdout";
    
    # delegate the annoying work to SUPER...
    $r->SUPER::handler (@_);
    
    # read the headers from the file and delete it
    open FP, "<$filename";
    while (<FP>) {
	$headers .= $_;
	last if (/^$/);
    }
    close FP;
    unlink ($filename);
    
    # restores STDOUT
    close (STDOUT);
    open (STDOUT, ">&OLDOUT");
    
    # and print the headers
    $r->print ($headers);
}


1;
