#!/usr/bin/env perl

# Stupid script to strip trash formatted filenames

use strict;
use warnings;

my @inputs = @ARGV;

sub strip_filename($) {

my $filename = shift;
my @chars = split("",$filename);
my $new_filename;
open(my $fh, ">>", \$new_filename) or die "Couldn't open new_filename var\n";
foreach my $char ( @chars ) {
if ( $char =~ m/\s/ ) {
next;
} elsif ( $char =~ m/\(|\)|\\|\'|\$|\!|,|\[|\]/ ) {
next;
} else {
print $fh $char;
}
}
close $fh;
return $new_filename;
}

sub construct_mv_fn($) {

my $filename = shift;
my @chars = split("",$filename);
my $new_filename;
open(my $fh, ">>", \$new_filename) or die "Couldn't open new_filename var\n";
foreach my $char ( @chars ) {
if ( $char eq " " ) {
print $fh "\\$char";
} else {
print $fh $char;
}
}
close $fh;
return $new_filename;

}

sub rename_file($$) {

my ( $old_filename, $new_filename ) = @_;
my $mv_filename = construct_mv_fn($old_filename);
my $cmd = "mv '$mv_filename' $new_filename";
print "$cmd\n";
#system("$cmd");

}

foreach my $input ( @inputs ) {
if ( ! -f $input ) {
print "File at path $input doesn't look like a file\n";
exit 1;
}
print "$input\n";
my $new_filename = strip_filename($input);
print "$new_filename\n";
rename_file($input,$new_filename);
}