#!/usr/bin/perl

# Move time codes to end of each line
# and clean some other stuff up if needed

use strict;
use warnings;

if ( ! defined $ARGV[0] ) {
print "Need to pass track list\n";
exit 1;
}

my $file = shift(@ARGV);

foreach my $line ( split("\n", `cat $file`) ) {
chomp $line;
if ( $line =~ m/([0-9]{2}:[0-9]{2}|[0-9]{1,2}:[0-9]{2}:[0-9]{2})/ ) {
my $time_code = $1;
$line =~ s/ $time_code//g;
$line = $line . " " . $time_code;
}

if ( $line !~ m/^[0-9]{1,2}\./ ) {
$line =~ s/^([0-9]{1,2})//g;
my $track_number = $1;
$line = "$track_number" . "." . "$line";
}

my $sanitized_line;
open(my $fh, ">>", \$sanitized_line);
my @line_chars = split("",$line);
foreach my $char ( @line_chars ) {
if ( $char !~ m/[a-zA-Z0-9:\s\.-]/ ) {
$char = "";
print $fh "$char";
} else {
print $fh "$char";
}
}

close $fh;
print "$sanitized_line\n";

}