#!/perl -w
# NAME: chkdupes.pl
# AIM: Read a folder, and subfolders, and check for any duplicate file names
# This is so they can all be put in one folder, if possible
use strict;
use warnings;
use File::stat;
use File::Basename;
unshift(@INC, 'C:/GTools/perl');
require 'logfile.pl' or die "Unable to load logfile.pl ...\n";
# log file stuff
my ($LF);
my $pgmname = $0;
if ($pgmname =~ /\w{1}:\\.*/) {
	my @tmpsp = split(/\\/,$pgmname);
	$pgmname = $tmpsp[-1];
}
my $outfile = "temp.$pgmname.txt";
open_log($outfile);

my $def_folder = "C:\\Users\\Public\\SAVES\\peru\\My Pictures\\Carla";	# DEFAULT, if NO command input
my $in_folder = $def_folder;
if (@ARGV) {
	$in_folder = pop @ARGV;
}
my @file_list = ();
my $incnt = 0;
my %exthash = ();
my $file = '';
my $name = '';
my @dup_list = ();

prt( "$0 ... Processing $in_folder ...\n" );

process_folder($in_folder);
$incnt = scalar @file_list;
prt( "Got $incnt file items to check ...\n" );
for (my $i = 0; $i < $incnt; $i++) {
	$name = $file_list[$i][1];
	for (my $j = 0; $j < $incnt; $j++) {
		if ($i != $j) {
			if ($name eq $file_list[$j][1]) {
				$file_list[$j][2]++;
				$file_list[$i][2]++;
			}
		}
	}
}
for (my $i = 0; $i < $incnt; $i++) {
	$name = $file_list[$i][1];
	if ($file_list[$i][2] > 0) {
		#prt( "Dupe $name ...\n" );
		prt( "del \"$file_list[$i][0]\"\n" );
	}
}

foreach my $key (keys %exthash) {
	prt( "Extension $key occurs ".$exthash{$key}." times ...\n" );
}

close_log($outfile,1);
exit(0);

sub process_folder {
	my ($inf) = shift;
	my @subdirs = ();
	if (opendir( DIR, $inf)) {
		my @files = readdir(DIR);
		closedir DIR;
		foreach $file (@files) {
			if (($file eq '.')||($file eq '..')) {
				next;
			}
			my $ff = $inf . "\\" . $file;
			if (-d $ff) {
				push(@subdirs,$ff);
			} else {
				my ($nm,$dir,$ext) = fileparse( $ff, qr/\.[^.]*/ );
				#my ($nm,$dir) = fileparse( $ff );
				$nm = lc($nm);
				$ext = lc($ext);
				$name = $nm.$ext;
				push( @file_list, [$ff, $name, 0] );
				if (defined $exthash{$ext}) {
					$exthash{$ext} ++;
				} else {
					$exthash{$ext} = 1;
				}
			}
		}
		foreach my $fil (@subdirs) {
			process_folder($fil);
		}
	} else {
		prt( "ERROR: Can NOT open $inf ... $! ... \n" );
	}
}

# eof
