#!/usr/local/bin/perl -w

# Add a new suffix to the synphot throughput tables
#
# Usage: addsuffix [directory]
# directory is the top level directory of the throughput tables
# if no directory is specified, it uses the current directory
#
# The new suffix is added just before the extension and separated by
# an underscore from the preceding name, as per the usual conventions

use File::Find;

#----------------------------------------------------------------------
# Configuration variables. 

# The suffix to add to the throughput tables
$suffix = 'syn';

# The extension of the throughput tables
$extension = 'fits';

# The default top level directory to search for throughput tables
$default_dir = '.';

#----------------------------------------------------------------------

# Find traverses the directory tree, calling addsuffix on each file

$directory = $ARGV[0] || $default_dir;
find (\&addsuffix, $directory);

#----------------------------------------------------------------------
# Rename a file by adding a new suffix

sub addsuffix {
    # The filename this function is called with is stored in $_

    $old = $_;

    # Only change file with proper extension that haven't
    # been changed already

    return if $old !~ /\.$extension$/o;
    return if $old =~ /_$suffix\.$extension$/o;

    # Make new file name. Assumes only one dot in the name

    $new = $old;
    $new =~ s/_(\d+)\./sprintf ('_%03d.', $1+1)/e;
    $new =~ s/\./_$suffix\./o;

    # Rename the file

    rename $old, $new;
    print "$old -> $new\n";
}

