#!/usr/bin/env perl -w
###############################################################################

use strict;
use File::Find;
use File::Basename qw( basename );

my ($DEBUG, $BLANK, $prog) = (0, 0, basename($0));

my $usage = "
Usage:
  $prog [-debug] [-blank] [dir ...]
";

###############################################################################

sub is_wanted_dir($)
{
   my ($s) = @_;
   return ( $s !~ m!^(\.|CVS)!o );
}

sub is_wanted_file($)
{
   return 1; # all files accepted
}

###############################################################################

my %Ext;
my $Cnt;

sub start($)
{
   %Ext = ();
   $Cnt = 0;
}

sub process_file($$)
{
   my ($n, $p) = @_;
   if ( $n =~ m!\.([^.]+)$!o ) { ++$Ext{lc($1)}; } else { ++$Ext{""};  }
   ++$Cnt;
}

sub finish($)
{
   my ($dir) = @_;
   print "$dir [$Cnt] {\n";
   for my $x (sort keys %Ext)
   {
      print sprintf("  .%-8s= %d\n", $x, $Ext{$x});
   }
   print "}\n";
}

###############################################################################

sub wanted_source()
{
   return unless( -f );
   return unless( is_wanted_file($_) );
   process_file($_, $File::Find::name);
}

sub preprocess_dir()
{
   my @r = ();

   for my $s (@_)
   {
      if    ( -d $s ) { next unless is_wanted_dir($s);  }
      elsif ( -f $s ) { next unless is_wanted_file($s); }
      else            { next;                           }

      push(@r, $s);
   }

   if ( $DEBUG >= 2 )
   {
      print "preprocessed ", $File::Find::dir, ": {\n  ";
      print join("\n  ", @r);
      print "\n}\n";
   }

   return @r;
}

sub scan_directory($)
{
   my ($dir) = @_;

   if ( -d $dir )
   {
      start($dir);
      find({ wanted=> \&wanted_source, preprocess=> \&preprocess_dir }, $dir);
      finish($dir);
   }
   else
   {
      print "  ERROR -- directory doesn't exist -- $dir\n";
   }
}

###############################################################################

my @dirs = ();

while ( my $o = shift @ARGV ) {
   if    ( $o =~ m!^-?(d|dbg|debug)$!io   )  { ++$DEBUG; }
   elsif ( $o =~ m!^-?(0|dummy|blank)$!io )  { ++$BLANK; }
   elsif ( -d $o )                    { push(@dirs, $o); }
   else                                    { die $usage; }
}

@dirs = ( "." ) unless scalar(@dirs) > 0;
for my $d ( @dirs ) { scan_directory( $d ); }

###############################################################################
1;
