# # (gH)   -_-  renomme.pl  ;  TimeStamp (unix) : 22 Avril 2016 vers 17:13

#################################################################################
#
# this script renames all files corresponding to $before
# by replacing $before with $after.
#
# for instance with $before = "_001.fastq" and $after = ".fastq"
# the files Aba1_S1_L001_R1_001.fastq, Xa1_S2_L001_R2_001.fastq...
# will be renamed Aba1_S1_L001_R1.fastq, Xa1_S2_L001_R2.fastq
#
#################################################################################

use strict ;
use warnings ;

if ($#ARGV==-1) {
  print "\n" ;
  print " the script renomme.pl renames all files corresponding to the substring BEFORE \n" ;
  print " by replacing BEFORE with AFTER\n\n" ;
  print "syntax   : perl renomme.pl BEFORE AFTER      \n" ;
  print "examples : perl renomme.pl _OO1.fastq .fastq \n" ;
  print "           perl renomme.pl _XX1.fastq R1.fastq \n" ;
  print "\n\n" ;
  exit(-1) ;
} ; # end if

if ($#ARGV==0) {
  print "Argument 2 is missing.\n" ;
  print "Syntax is  : perl renomme.pl BEFORE AFTER \n" ;
  exit(-1) ;
} ; # end if

my $before = $ARGV[0] ;
my $after  = $ARGV[1] ;
my @files  = glob("*".$before."*")  ;

# warn if no file corresponds to the specification

my $nbf = @files ;
if ($nbf==0) {
  print("\nAlas, no files corresponds to the specification \"$before\". Nothing to do !\n\n") ;
} else {
  my $msg = "Renaming $nbf file(s) corresponding to the specification \"$before\"." ;
  my $sou = "=" x length($msg) ;
  print "\n".$msg."\n".$sou."\n\n" ;
} ; # end if

foreach my $file (sort @files) {
  my $newFile =  $file ;
  $newFile    =~ s/$before/$after/ ;
  if ($file ne $newFile) {
     if (-e $newFile) {
        print("File $newFile already exists, file $file will not be renamed.\n") ;
     } else {
        if (rename($file,$newFile)) {
          print("File $file has been renamed $newFile\n") ;
        } else {
          print("Cannot rename file $file as $newFile\n") ;
        } ; # end if
     } ; # end if
  } ; # end if
} ; # end of foreach

# end of script
