#!/usr/bin/env perl
use strict;
use File::Find;
#
# Extract man entries embedded in *.c and *.v files.  Save the entries
# to the file doc/automan.doc.  See below __END__ for an example of an
# embedded man entry.
# 
# Albert Danial    November 27 2001
#

my $location = `pwd`;
my $PATH     = "";
if ($location =~ m{^(.*)/admin$}) {
    chdir "..";
    $PATH = "$1/";
}

my @files = ();      # populated in wanted()
find(\&wanted, "."); # recursively descend directory looking for *.[cv] files

my $nEntries = 0;
my $doc_file = "doc/automan.doc";
open(OUT, ">$doc_file") or die "Cannot write to $doc_file:  $!\n";
foreach my $F (@files) {
    $F =~ s{^\./}{};   # strip leading    ./
    my $in_man     = 0;
    my $entry_name = "";
    open(IN, $F) or die "Cannot read $F:  $!\n";
    while (<IN>) {
        if (!$in_man and 
             m=^\s*(/?\*|\\|{?#+)?\s+man\s+entry:\s+(\S+)\s+{{{2\s*$=
             ) {
            $entry_name = $2;
            $in_man     = 1;
            ++$nEntries;
        } elsif ($in_man and m/2}}}/) {
            print OUT "$entry_name defined:  $F, line $.\n";
            $in_man     = 0;
        } elsif ($in_man) {
            s=^\s*(/?\*|\\|#+)?\s*==;
            print OUT "$entry_name $_";
        }

    }
    close(IN);
}
close(OUT);
die "Could not find any embedded documentation in *.c or *.v files\n"
    unless $nEntries;
print "Wrote $nEntries entries to $doc_file\n" if $nEntries > 1;
print "Wrote $nEntries entry to $doc_file\n" if $nEntries == 1;

# populate @files:
sub wanted { 
    # ignore files in code template directory
    return if $File::Find::dir =~ m{admin/templates};
    push @files, "$File::Find::dir/$_" if /\.[cvn]$/; 
}
__END__
/* 
 * man entry:  sparse {{{2
 * (hA --- hA_sp) takes a dense matrix and converts it to sparse form
 * category: math, sparse
 * related:  dense, spbend, spadd, sprand
 * 2}}} 
 */
