#!/usr/bin/perl -w
use strict;

sub filelist
{
    my ($dir, $regex) = @_;
    opendir(DIR, $dir) || return ();
    my @files = grep { /$regex/ } readdir(DIR);
    closedir DIR;
    @files; 
}

sub dirlist 
{
    my ($dir) = @_;
    opendir(DIR, $dir) || return ();
    my @dirs = grep { -d $dir.'/'.$_ && $_ ne '.' && $_ ne '..' } readdir(DIR);
    closedir DIR;
    @dirs; 
}

my $FROM;
my $TO;

sub run 
{
    my ($path) = @_;
    $path .= '/' unless $path =~ m!\/$!;
    my @dirs = dirlist($path);
    
    my @files = filelist($path, '.*');
    foreach my $file(@files) {
	my $newfile = $file;
	$newfile =~ s/$FROM/$TO/g;
	if ($newfile ne $file) {
	    print "Renaming $path$file to $newfile\n";
	    `mv $path$file $path$newfile`;
	}
    }

    foreach my $dir(@dirs) {
	run($path.$dir);
    }
}

if (@ARGV != 3) {
    print "Arguments: <path> <from> <to>\n",
    "           <from> and <to> are regular expressions\n";
    exit;
}

$FROM = $ARGV[1];
$TO = $ARGV[2];
run($ARGV[0]);

__END__
