#!/usr/bin/perl
use Cwd;
print "-------------------------------------------------------------\n";
print "lowernames by Lauri Laitinen\n";
print "The program converts file and directory names to lower case\n";
print "in current working directory and recursively in subdirections\n";
print "-------------------------------------------------------------\n";
my $juuri=cwd();
print "JUURI=$juuri\n";
#my $juuri='.';
my $rivi; my ($filelkm,$dirlkm)=(0,0);
handle_a_directory ($juuri);
print "DIR_LKM =$dirlkm\n";
print "FILE_LKM=$filelkm\n";
1;

sub handle_a_directory {
    my ($dir)=@_;
    my $rivi=sprintf("*** DIRECTORY: %s ***\n",$dir); print $rivi;
    my $f,$ff;
    foreach $f (nimilista($dir)) {
       if (($f eq '.') or ($f eq '..') ) {next}
       my $new=muunna($f);
       my $fPath="$dir/$f"; my $newPath='';
       if (-d $f) {
          if ($new) {
	      my $newPath="$dir/$new";
	      my $ok=rename($fPath,$newPath);
	      if (!$ok) {
	         error_print("Can not rename $fPath to $newPath\n");
	      }
	      $ff=$new
          } else {$ff=$f}
          my $rivi=sprintf("DIR: %s -> %s\n",$fPath,$newPath);
          print $rivi;$dirlkm++;
          handle_a_directory("$dir/$ff");
       } else {
          if ($new) {
             $newPath="$dir/$new";
	     rename($fPath,$newPath);
          }
          my $rivi=sprintf("%s -> %s\n",$fPath,$newPath);
          print $rivi;  $filelkm++;
       }
    }
}

sub nimilista {
    my ($dir)=@_;
    opendir(DIR,$dir) or die ("Can not open $dir\n");
    my @lista=readdir(DIR); close DIR;
    return @lista;
}

sub muunna {
    my ($old)=@_;
    my $new=$old; $new=~tr/A-Z/a-z/;
    #print "OLD=$old NEW=$new\n";
    if ($new ne $old) {return $new} else {return ''}
}

sub error_print {
    my ($error_text)=@_;
    print $error_text;
    exit 0;
}
