#!/usr/bin/perl 
use strict;
use warnings;

use File::Find;

our $nFilesRenamed = 0;
our $nFilesDeleted = 0;

my $finalize = 'true';   # set this to true if you want to finalize the new file as the final version (otherwise, reverts)
my $noSave = 'true';  # set this to true if you want to delete the original file (only used if $finalize is true)

sub do_substitutions {
	my $origSuffix = '_orig';
	my $suffixLen = length ($origSuffix);
	my $tempSuffix = '_temp';
	

    # substitute strings here
    # First print file name
    my $currentFileName = $File::Find::name;
    print "\tNow on $currentFileName ...\n";
    if (-f) {
   
	    if ((my $shortFileName = $currentFileName) =~ s/$origSuffix//)  {
	    
	        if (! $finalize) {
	        
	    		print "\tWill rename $currentFileName to $shortFileName -- has original suffix.\n";
	  	        rename ($currentFileName, $shortFileName) or die ("Can't rename $currentFileName!");
	  	        $nFilesRenamed++;
	        	
	        } elsif ($finalize && $noSave) {
	        
	        	print "\tWill delete $currentFileName (the original).\n" ;
	        	unlink ($currentFileName) or die ("Can't delete $currentFileName!");
	        	$nFilesDeleted++;
	        }
	    }
	    
	    if ((my $shortFileName = $currentFileName) =~ s/$tempSuffix//) {
	    
	        if (! $finalize) {
	        
		        print "\tWill delete $currentFileName -- has temporary suffix.\n";
		        unlink ($currentFileName) or die ("Can't delete $currentFileName!");
		        $nFilesDeleted++;
		        	        
		    } elsif ($finalize) {
	        
	        	print "\tWill rename $currentFileName (has temporary suffix) to final.\n" ;
	        	rename ($currentFileName, $shortFileName) or die ("Can't rename $currentFileName!");
	        	$nFilesRenamed++;
	        }

	    }
	    
	}
    
}
    
    
@ARGV = ("/Users/graybeal/Desktop/RoverConversionData") unless @ARGV;

if ($finalize) {
    print "The 'finalize' option has been set. Temporary files will be renamed to final.\n";
	if ($noSave) {
	    print "The 'no save' option has been set. Original files will be deleted.\n";
	}
}


find (\&do_substitutions, @ARGV);

print "Done.\n\tFiles renamed: $nFilesRenamed\n\tFiles deleted: $nFilesDeleted\n" ;