#!/usr/local/bin/perl
# This script will upcase all the files in the current working directory

# first, check to see if there are any arguments.  If none, print usage

$num = @ARGV;
if ( $num == 0 ) {
	die "Usage: upcase.pl <directory>\n";
}

# Check to see if object is file or link.  If so, rename it now and exit

$file = @ARGV[0];
if ( -f $file || -l $file ) {
	$ufile = "\U$file";
	rename ($file,$ufile) || die "Couldn't rename file $file \n"

# check to see if it is a directory.  If so, call "rendir" subroutine with
# this name

} elsif ( -d $file ) {
	$topdir = $file;
	&rendir("$file");

# Neither file, link or directory.  Either it is not here, or it is a special
# file that needs to be handled elsewhere

} else { die "This is not a normal file - please double check it and rename
manually";
}

# rename a dir and its contents to upper case.  We expect to be called like:
#       rendir(directory);

sub rendir {

# localize and initialize variables

        local($dir, $file, $DIR);
        $dir = $_[0];
        $DIR = "\U$dir";

# open directory handle and move to that directory

        opendir($DIR, "$dir") || die "Couldn't open $dir.\n";
        chdir("$dir") || die "Couldn't change to $dir.\n";

# this is the main loop.  Read files from the directory.  Upcase the name.
# if it is a directory, recursively call this subroutine. 

        while ($file = readdir($DIR)) {
		$ufile = "\U$file";
                if (-d $file) {
                        if ($file ne "." && $file ne "..")
{&rendir("$file");}
                }

# if it is a file, make sure it is not already upcased

                elsif ( $file eq $ufile ) { next }

# it's a lower case file - make it uppercase

		else { rename($file,$ufile); }
        }

# go home, close the dir-handle and don't forget to rename the directory
itself!

        chdir("..");
        closedir("$DIR");
	if ( $dir eq $topdir ) {
		if ( $dir eq $DIR ) { 
			$dir = "\L$DIR\E"; 
			rename($DIR,$dir)
		}
		if ( system("cp -R $dir $DIR 2>/dev/null") ) {
			system("cp -r $dir $DIR");
			system("rm -r $dir");
		} else { system("rm -R $dir");
		}
	} else {
		rename($dir,$DIR);
	}
}