#!/usr/local/bin/perl -w-- # -*- perl -*-
#
# $Id: nfiles_one_level,v 1.1 1996/12/30 22:06:17 ejb Exp $
# $Source: /home/ejb/scripts/RCS/nfiles_one_level,v $
# $Author: ejb $
#

# This code, from the perl manual page, forces this to be run by perl from 
# perl, sh, or csh.  It must be first.
eval '(exit $?0)' && eval 'exec /usr/local/bin/perl -S $0 ${1+"$@"}'
& eval 'exec /usr/local/bin/perl -S $0 $argv:q'
    if 0;

$whoami = ($0 =~ m,([^/]*)$,) ? $1 : $0;

$| = 1;
$a = $b = "";			# prevent warnings
$trash = "";
@trash = ();
$xdev = 0;
if (defined($ARGV[0]) && ($ARGV[0] eq "-xdev"))
{
    $xdev = 1;
    shift(@ARGV);
    
}
$dir = $ARGV[0] || ".";
$dir =~ s,/$,,;
@dirs = ($dir);

$topdev = (stat($dir))[0];

#
# Do a breadth-first traversal of the filesystem counting up usage of
# files and putting directories on the stack.
#
while(@dirs)
{
    $dir = shift(@dirs);
    opendir(DIR, $dir);
    @entries = readdir(DIR);
    splice(@entries, 0, 2);	# kill . and ..
    @entries = sort { $a cmp $b } @entries;
    closedir(DIR);
    $n = 0;
    for (@entries)
    {
	$n++;
	$file = "$dir/$_";
	if ((-d $file) && (! -l $file))
	{
	    $dev = (stat($file))[0];
	    if (! ($xdev && ($dev != $topdev)))
	    {
		push(@dirs, $file);
	    }
	}
    }
    printf("%4d  $dir\n", $n);
}

sub usage {
    print STDERR "Usage: $whoami [-xdev] [dir]\n";
    exit 1;
}
