#!/usr/bin/perl -w
use strict;

#person in charge of this script
#this should be the person currently in charge of scripts for this project
my $script_maintainer='Teri Solow <tms45@cornell.edu>';


@ARGV or print "No input parameters, proceeding with default.\n";

my @arg_pairs = split (/\-/, (join ' ', @ARGV));

my %args=();

foreach (@arg_pairs){

    $_ or next;
    my ($flag, $val)=split /\s+/;
    $args{$flag}=$val;
}

my $in_dir=$args{'i'};
my $out_dir=$args{'o'};
my $old_lib_name=$args{'m'};
my $new_lib_name=$args{'n'};
my $project=$args{'p'};


$project or die "Please specifiy a project (fgn, cgn or pgn) with the -p flag\n";

$old_lib_name or die "no old name specified\n";
$new_lib_name or die "no new name specified\n";

#set defaults for io, script filename, etc
$in_dir ||= "/data/shared/pgn_data_processing/trace_files/".$project;
$out_dir ||= "/data/shared/pgn_data_processing/trace_files/".$project;



#uniform trailing slashes
$out_dir=~/\/$/ or $out_dir.='/';
$in_dir=~/\/$/ or $in_dir.='/';



#main body of script
#####################


#make a list of zip files in the incoming directory
#unzip them into the target dir, making subdirs as needed
#remove sequence files
#zip individual tracefiles and remove original trace

my @all_files=&traverse_dir($in_dir);


print "Found " . int(@all_files) . " files to process \n";

foreach (@all_files){


    /$old_lib_name([^\/]*)$/ or next;

    my $start_file=$_;
    my $new_file=$start_file;
    $new_file =~ s/$old_lib_name([^\/]*)$/$new_lib_name$1/;

    print "Renaming $start_file to $new_file.\n";

    my $syscmd="mv $start_file $new_file";
#    system($syscmd);
#    print "$syscmd\n";

}






#sub to recursively traverse directories and build a list of file names
#######################
sub traverse_dir{
    my ($dirarg)=@_;
    opendir (THISDIR, $dirarg) or die "Couldn't open directory $dirarg\n";
#skip any files starting with .
    my @dir_list= grep !/^\./, readdir THISDIR;
    my ($filename, @filelist);
    foreach $filename (@dir_list){
	$filename=$dirarg.$filename;
	if(-d $filename){
	    $filename.='/';
	   push @filelist,  &traverse_dir($filename); 
       }
	else{
	    push @filelist, $filename;
	}
    }
    return @filelist;
}



