#! /usr/bin/perl
use warnings;
use strict;
use integer;
use FindBin;
use lib $FindBin::RealBin;
use Def;

# This script counts and ranks dependencies in one or more Packages
# files.

our $usage = <<END;
usage: $0 [-h] [Packages file]...
    -h print this usage message
END

# Read command-line arguments and options.
my @opt;
my @arg;
{
  my $stopopt = '';
  for ( @ARGV ) {
    if    ( $stopopt  ) { push @arg, $_        }
    elsif ( $_ eq '-' ) { $stopopt = '1'       }
    else  { push @{ /^-/ ? \@opt : \@arg }, $_ }
  }
}
my %opt = map { my @o = split ''; shift @o; map {$_=>1} @o; } @opt;
if ( $opt{'?'} || $opt{h} ) { print $usage; exit 0; }

my %dep;

for my $fn ( @arg ) {
  open  P, '<', $fn;
    while (<P>) {
      my( $text ) = /^(?:Pre-Depends|Depends|Recommends):(.*)$/ or next;
      $dep{$_}++ for map { length($_) ? $_ : () }
        split /[\s,|]*\([^()]*\)[\s,|]*|[\s,|]+/, $text;
    }
  close P;
}

printf "%5d %s\n", $dep{$_}, $_ for sort {
  $dep{$b} <=> $dep{$a} || $a cmp $b
} keys %dep;

