#!/usr/bin/perl

$BINSIZE = 1024;

$nfiles = 0;
$largest_bin = 0;

$filesystem = shift @ARGV;

&find($filesystem); # sets global @FILES

foreach $_ (@FILES) {
	($mtime, $size, $file) = split;

	if ($size == 0) {
		next;
	}

	++$nfiles;
	$total += $size;

	$bin = int($size / $BINSIZE);
	if ($bin > $largest_bin) {
		$largest_bin = $bin;
	}
	++$histo[$bin];
}

printf "%d files\n", $nfiles;
printf "%d total bytes\n", $total;
printf "%d avg bytes\n\n", $total/$nfiles;

$sum = 0;

for($i = 0; $i < $largest_bin; ++$i) {
	$sum += $histo[$i];
	if ($histo[$i] != 0) {
		printf "< %dk %d %d%%\n",
			(($i+1) * $BINSIZE) / 1024, $histo[$i], $sum * 100 / $nfiles;
	}
}

exit;

# look ma, no hands.

sub
find
{
	local($path) = @_;
	local(*DIR, $_);

	#DEBUG#printf "%s:\n", $path;

	opendir(DIR, $path);
	while( $_ = readdir(DIR))
	{
		next if /^\.$/;
		next if /^\.\.$/;

		if ( -d "$path/$_" && ! -l "$path/$_" )
		{
			#debug#printf "\n";
			&find("$path/$_");
		}
		else
		{
			#debug#printf "%s\n", $_;

			($dev, $ino, $mode, $nlink, $uid, $gid, $rdev, $size,
				$atime, $mtime, $ctime ) = stat("$path/$_");

			push(@FILES, "$mtime $size $path/$_");
		}
	}
	closedir(DIR);
}

sub
df
{
	$_ = shift @_;
	local($device, $type, $size, $used, $avail, $percent, $filesystem);

	($device, $type, $size, $used, $avail, $percent, $filesystem)  = split(' ', `df $_ | tail -1`);

	return ($size*1024, $used*1024);
}
