#! /usr/bin/perl -w
    eval 'exec /usr/bin/perl -S $0 ${1+"$@"}'
        if 0; #$running_under_some_shell

# http://twiki.org/cgi-bin/view/Codev/FindReferencedButNotDefinedWikiWords

use strict;
use File::Find ();
# Set the variable $File::Find::dont_use_nlink if you're using AFS,
# since AFS cheats.

my $datadir = "/home/james/twiki/data";
my @weblist = ( "Know", "Main", "Test", "Trash", "TWiki" );

# Changing the value to 0 seems to make things work  -- Main.KevinCounts - 10 Jan 2005
# my $dangle_threshold = 1;

my $dangle_threshold = 0;

my (%got, %dangling);

my $compundRegexp =
qw!([\*\s][\(\-\*\s]*)([A-Z]+[a-z0-9]*)\.([A-Z]+[a-z]+[A-Z]+[a-zA-Z0-9]*)!;
my $simpleRegexp =
qw!([\*\s][\(\-\*\s]*)([A-Z]+[a-z]+[A-Z]+[a-zA-Z0-9]*)!;

foreach my $current_web ( @weblist ) {
    my $top = $datadir . "/" . $current_web;
    %got = ();      File::Find::find({wanted => \&remember_got}, $top);
    %dangling = (); File::Find::find({wanted => \&search_it   }, $top);
    
    foreach (sort { $dangling{$b} <=> $dangling{$a} } keys %dangling) {
        if ($dangling{$_} > $dangle_threshold) {
            printf("%3d : %s.%s\n", $dangling{$_}, $current_web, $_);
        }
    }
    print "\n";
}

sub remember_got { if (m/([^\/]+)\.txt\z/s) { $got{$1} = 1; } }
sub compound { }   # ToDo: implement me later.
sub simple { if (!$got{$_[0]}) { ++$dangling{$_[0]}; } }

sub search_it {
    if (m/([^\/]+)\.txt\z/s) {
        open INFILE, "<$_";
        while (<INFILE>) {
            s/$compundRegexp/&compound($2,$3),""/geo;
            s/$simpleRegexp/&simple($2),""/geo;
        }
        close INFILE;
    }
}
