#!/usr/bin/perl -w
#
# This file is used to redirect bweb to the exact file of the documentation
#
use strict;
use CGI;
use JSON qw( encode_json );

# Creation mode, put the directory to scan in argument
if (scalar(@ARGV) > 0) {
    my %index;
    my $dir = $ARGV[0];
    # Index this directory
    open(FP, ">docs.json") or die "ERROR: unable to open index file";

    chdir($dir) or die "ERROR: Unable to chdir to $dir";

    foreach my $l (`grep -i '<a name="' *.html`) {

        # Monitor_Configuration.html:<A NAME="MonitorResource"></A>
	my $file;
	if ($l =~ m/^([^:]+):/) {
	   $file = $1;	
	} else {
	   next;
	}
        while ($l =~ m/<A NAME="(.+?)">/ig) {
            my $key = $1;
            if ($key !~ /^(tex2html|\d|SECTION|fig)/) {
                $index{$key} = $file;
            }
        }
    }

    print FP encode_json(\%index);
    close(FP);
    exit;
}