#!/mesa/bin/perl -w
use strict;

my $dir = $ENV{MESA_PLAYGROUND}."/psp/lib";
chdir $dir or die "chdir: $dir\n";
chomp(my @files = `find -name '*.pm' | egrep -v PreScan`);

my %tags;
for my $file (@files) {
  open FILE, $file or die "open: $file: $!\n";
  my $cur_package = "main";
  while(<FILE>) {
    if (/^package ([^;]+);/) {
      $cur_package = $1;
      next;
    }
    if (/^sub (begin|end)_((psp)?(\w+))/) {
      my $tagname = $4;
      $tags{$tagname}->{$1}++ and warn "'$tagname' not unique.\n";
      $tags{$tagname}->{name} = $4;
      $tags{$tagname}->{psp} = $3;
      $tags{$tagname}->{pkg} = $cur_package;
    }
    if (/->([\:\w+]+::)?(begin|end)_((psp)?(\w+))/) {
      $tags{$5}->{used}->{$cur_package}++;
    }
  }
}

for my $tagname (sort{ $tags{$a}->{pkg} cmp $tags{$b}->{pkg} or $a cmp $b } keys %tags) {
  my $tag = $tags{$tagname};
  my @notes;
  printf "%-15s %-30s ", $tag->{name}, $tag->{pkg},;
  push @notes, "no begin" unless $tag->{begin};
  push @notes, "no end"   unless $tag->{end};
  push @notes, "no psp"   unless $tag->{psp};
  push @notes, "used by ".join(",",sort keys %{$tag->{used}}) if $tag->{used};
  print join(", ",@notes)."\n";
}
