#!/usr/bin/perl

# Rename filename of format nn* where nn is a two (or more) digit
# number to a different offset.
#
# Usage:  offset [-t] 53 *.wav
#
#   Renames 01.wav, 02--Tune.wav... to 53.wav 54--Tune.wav...
#
# Rev 2.0 - Modified so that the number does not have to be
# at the start of the filename.
#
# Rev 2.1 - Fixed regex so that the 3 in names like "01.mp3" do not
# play into the renaming process.

if ($#ARGV <= 0) {
 print << 'ENDPRINT';

Version 2.0 - David Edwards, 1/25/2014

offset - Given a filename with format "*nn*", where nn is a two 
(or more) digit number.  Rename the file(s) to a different offset
as follows:
		 
             *nn* -->  nn+offset-1  

  Usage:  offset [-t] OFFSET file_name...

  Example:  offset 005 01.wav 02--Tune.wav
  
  Renames: 01.wav       --> 005.wav
           02--Tune.wav --> 006--Tune.wav        

  The number of digits in the renamed file will
  match the number of digits in OFFSET.

  -t    Only print what would be renamed. Don't actually
        rename any files.

ENDPRINT
 exit 1;
}

if ($ARGV[0] =~ /^-t/i) {
	shift;
	$f_test = 1;
}

$offset = $ARGV[0];

$abs_offset = $offset;
$abs_offset =~ s/\D+//;
$numdigits=length($abs_offset);
$fmt="%0${numdigits}d";

shift;

$subdir="offset.$$";

mkdir($subdir,0777) || die "Cannot make directory $subdir: $!";

foreach $fname (@ARGV) {

	$fname =~ /(\d+)/;
	$num = sprintf($fmt,$1 + $offset - 1);

	$newname = $fname;
	$newname =~ s/\d+/$num/;
	
	print "$fname -> $newname\n";

	if (! $f_test) {
		rename("$fname","$subdir/$newname") || 
	   		die "Cannot rename $fname to $subdir/$newname";
	}
}

if (! $f_test) {
	`mv -i $subdir/* .`;
}

rmdir($subdir);

