#!/usr/bin/perl
#                                      Time-stamp: "2006-06-18 15:34:02 ADT"
# Rename items under the specified directories (or if none
#  specified, under the current directory), replacing spaces
#  (and other icky characters) with underscores.

use strict;
#use warnings;
BEGIN { $^W = 1}
use File::Find;
my @to_change;

@ARGV = ('.') unless @ARGV;

use Cwd;
my $start_dir = cwd;
my $x;
find( sub {
  return if $_ eq '.';
  $x = $_;

  if(
    grep $_, # like 'or' but without the short-circuiting
      $x =~ tr/\:/-/,
      $x =~ tr/\"/'/,
      $x =~ tr/[\<\>\\\:\*\"\|\?\; ]/__/,
      $x =~
    tr[\xc0\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf\xd0\xd1\xd2\xd3\xd4\xd5\xd6\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf\xe0\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef\xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff]
      [AAAAAAACEEEEIIIIDNOOOOOOUUUUYtsaaaaaaaceeeeiiiidnoooooouuuuyty]
      ,
      $x =~ tr/\x20-\x7E/_/c,
      (length($_) > 64) && do {
        if($x =~
	   #s<(\.[^\.\ \&\']{1,5})$><>s
	   s<(\.[a-zA-Z0-9\$\~\-\+]{1,5})$><>s
	    # Uhoh, it has an extension-- save it, and snip before it
	) {
          my $e = $1;
          $x = substr($x, 0, 65 - length($e)) . $e;
          #print "Now x <$x>\n";
        } else {
          $x = substr($x, 0, 65);
        }
        1;
      },
  ) {
    push @to_change, $File::Find::dir . '/' . $_,
                     $File::Find::dir . '/' . $x, ;
  }
}, @ARGV);
chdir($start_dir) || die "Can't chdir back to $start_dir: $!\nAborting";

my($from, $to);
while(@to_change) {
  ($from,$to) = splice @to_change, -2;
  print "$from -> $to\n";
  rename $from, $to or warn "Can't rename $from to $to -- $!";
}
exit;
__END__
