#!/usr/bin/perl
#
# File Name Fixer
#   usage: fixname <files>
#
# Renames files to comply with pwiggi's arbitrary standard
#
# This is pwiggi's standard:
#   1) all letters are lowercase
#   2) Whitespace becomes underscore
#   3) Never more than one consecutive underscore
#   4) No underscores flanking dashes
#   4) Never more than one consecutive dash
#
# ChangeLog:
#   0.2.4: More robust stripping of special characters
#   0.2:   Made everything more robust - better at multiple spaces and special
#          characters now.  Also now renumbering along with ds-audiotools
#   0.1.4: Added -o option, which prints to stdout instead of renaming the file
#   0.1.3: Added version variable
#   0.1.2: Added help message
#   0.1.1: Made code compile and run, no known bugs
#   0.1:   Switched code to perl with regular expressions
#   0.0.4: Minor bugs fixed, __ was becoming - instead of _
#   0.0.3: Minor bugs fixed, code improved
#   0.0.2: Takes command-line arguments instead of parsing entire directory
#   0.0.1: basic code in place

$VERSION = "0.2.4";
$HELP_MSG = "# Filename fixer v$VERSION\n\tusage: fixname <files>\n\t       fixname -o \"name\"\n";

die $HELP_MSG if ($#ARGV < 0);
foreach (@ARGV)
{
    die $HELP_MSG if (/^(--help)|(-h)$/);
    if (/^-o$/)
    {
	$toStdOut = true;
    }
}

@ARGV = grep(!/^-o$/, @ARGV) if ($toStdOut);

foreach (@ARGV)
{
    my $oldname = $_;

    s/(.*)/lc($1)/e;  # Lowercase it
    s/[()\[\]{}!@#\$%^*,;:\'~]//g;  # Remove odd characters that could break bash

    s/[&]/and/g; # & to 'and'

    s/\s/_/g;          # Change whitespace to _
    s/_+/_/g;          # Squash multiple spaces
    s/\.+/\./g;          # Squash multiple dots
    s/^_*//;           # Remove leading space
    s/_*$//;           # Remove trailing space
    s/_*(-|\.)_*/$1/g; # Remove space flanking a - or .

    if ($toStdOut) { print; }
    else { system('mv', $oldname, $_); }
}


# Copyright (c) 2004 - 2010 John Wiggins
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA