#!/perl -w
# NAME: avsize.pl
# AIM: Given an input folder, give the avaerage SIZE of the files contained. Default is current folder ...
# 7/2/2008 - geoff mclane - http://geoffair.net/mperl/
use strict;
use warnings;
use File::Basename;
use File::stat;
use Cwd;
###unshift(@INC, 'C:/GTools/perl');

my @found_files = ();
my $in_folder = 'C:\HOMEPAGE\GA\travel\maroc\pics';

my ($file, $ff, $sb, $i);
my $cwdir = getcwd();
my $fndcnt = 0;
my $totsize = 0;
my $largest = 0;
my $smallest = 999999999999;
my $sz;
my $gotzero = 0;
my $avsize = 0;
my $msg = '';
my $dircount = 0;

$in_folder = $cwdir;
if (@ARGV) {
	$in_folder = pop @ARGV;
}

if ( opendir(DIR, $in_folder) ) {
	my @files = readdir(DIR);
	closedir DIR;
	prt( "Checking ".scalar @files." items in folder $in_folder ...\n" );
	foreach $file (@files) {
		if (($file eq '.')||($file eq '..')) {
			next;
		}
		$ff = $in_folder . "\\" . $file;
		if (-f $ff) {
			$sb = stat($ff);
			push(@found_files, [$ff, $sb->size, 0]);
		} else {
			# ignore directories (and others???)
			$dircount++;
		}
	}
	$fndcnt = scalar @found_files;
	prt( "Checking $fndcnt files in $in_folder ... ($dircount directories)\n" );
} else {
	prt( "Failed to open directory [$in_folder] ... check name, location ...\n" );
}
if ($fndcnt) {
	for ($i = 0; $i < $fndcnt; $i++) {
		$file = $found_files[$i][0];
		$sz = $found_files[$i][1];
		$totsize += $sz;
		if ($sz > $largest) {
			$largest = $sz;
		}
		if ($sz) {
			if ($sz < $smallest) {
				$smallest = $sz;
			}
		} else {
			$gotzero++;
		}
	}
	$avsize = int((($totsize / $fndcnt) + 0.5));
	if ($gotzero) {
		if ($fndcnt > $gotzero) {
			$fndcnt -= $gotzero;
			$avsize = int((($totsize / $fndcnt) + 0.5));
		}
		$msg = "(with $gotzero zero files)";
	}
	prt( "Largest ".get_nn($largest).", smallest ".get_nn($smallest)." bytes ... $msg\n");
	prt( "Average of $fndcnt files is ".get_nn($avsize)." ... total ".get_nn($totsize)." bytes\n" );
} else {
	prt( "WARNING: No files found ...\n" );
}

exit(0);

###########################
sub prt {
	my ($txt) = shift;
	print $txt;
}

##################################################
# My particular 'nice number'
sub get_nn { # perl nice number nicenum add commas
	my ($n) = shift;
	if (length($n) > 3) {
		my $mod = length($n) % 3;
		my $ret = (($mod > 0) ? substr( $n, 0, $mod ) : '');
		my $mx = int( length($n) / 3 );
		for (my $i = 0; $i < $mx; $i++ ) {
			if (($mod == 0) && ($i == 0)) {
				$ret .= substr( $n, ($mod+(3*$i)), 3 );
			} else {
				$ret .= ',' . substr( $n, ($mod+(3*$i)), 3 );
			}
		}
		return $ret;
	}
	return $n;
}

# eof - avsize.pl

