# rename.pl -- perl script, William Stein (was@mail.math.berkeley.edu)
# run by typing the following at a command prompt:
#    perl rename.pl
#
# Example:
# [was@descent file_names]$ perl rename.pl
# Rename filename tool, version 0.1
# by William Stein (was@mail.math.berkeley.edu)
# First input file: 2a09.tif
# String B: 2_
# First (3-digit) number XYZ: 009
# mv 2a09.tif 2_009.tif
# mv 2a10.tif 2_010.tif
#
##############################################################################
# I would like you to write (whenever it's convenient) a tool that will give #
# the files we have sensible names.  Recall that our files have names (for,  #
# say, SGA 1) of the form 1AXY.tif, where A is a lower-case letter and X and #
# Y are two digits.  I'd like to be able to convert these to the form        #
# BXYZ.tif, where B is some fixed string (e.g. "1_" or "4.5_") and X,Y, and  #
# Z are digits.  So, for instance, the files of SGA 1 could be changed from  #
# 1a01.tif ... 1i45.tif to 1_001.tif ... 1_375.tif.                          #
#                                                                            #
# More precisely, I'd like it to do this:                                    #
#                                                                            #
# Inputs: first input file, string B, first (3-digit) number XYZ             #
# Output: starting with the first input file and proceeding in               #
#  alphabetical order, rename the files to BXYZ.tif, increasing the          #
#  number XYZ once each time                                                 #
##############################################################################


print "SGA filename tool, version 0.1\n";
print "by William Stein (was\@mail.math.berkeley.edu)\n";

# will need the "chr NUMBER" function

sub increment {
    my $n = length($_[0]);
    my $prefix=substr($_[0],0,n-7);
    my $letter=substr($_[0],n-7,n-6);
    my $num=substr($_[0],n-6,n-4);
    $num++;
    my $new = $prefix.$letter.$num.".tif";
    if ($num > "99") {
       $num = "00";
       $letter = chr(ord($letter)+1);
       if (ord($letter) == ord("z")+1) {
           exit;
       }
       $new = $prefix.$letter.$num.".tif";
    }
    $new;
}

print "First input file: ";
chop($first = <STDIN>);
print "String B: ";
chop($B = <STDIN>);
print "First (3-digit) number XYZ: ";
chop($XYZ = <STDIN>);

while (1) {
    $newname = $B.$XYZ.".tif";
    print "mv $first $newname\n";
    system "mv $first $newname\n";
    $first = increment($first);
    while (!(-e $first)) {
       $first = increment($first);
    }
    $XYZ++;
}




