#!/usr/bin/env python
import sys
import glob
import re
import os


def cap_replacement(mo):
    return (mo.group(0).capitalize() + "_")


def split_words(in_str, delim, to_lower):
    """Look for upper-case letters, or non-alpha-numeric characters, and either
    add or replace with the delimiter."""

    if delim == '-': delim = r'\-'

    # make a copy.
    out_str = "%s" % in_str

    # Search on word boundaries; we're looking for sequences of:
    # * a lower-case followed by an upper-case character
    # * two or more upper-case followed by a lower-case character
    # * A numeric followed by an alphabetic character
    # * two or more alphabetic followed by a numeric character
    boundaries = [
            r"([a-z])([A-Z])",
            r"([A-Z]+)([A-Z][a-z])",
            r"([0-9]+)([a-z|A-Z]+)",
            r"([a-z|A-Z][a-z|A-Z]+)([0-9]+)" ]

    replace_term = "\g<1>%s\g<2>" % delim

    for search_term in boundaries:
        out_str = re.sub(search_term, replace_term, out_str)

    # turn all whitespace into delimiters
    out_str = re.sub("\s+", delim, out_str)

    # fix multiple delimiters in sequence
    search_term = r"%s+" % delim
    out_str = re.sub(search_term, delim, out_str)

    if to_lower == True:
        out_str = out_str.lower()

    return out_str


input_args = sys.argv

for arg in input_args[1:]:
    files = glob.glob(arg)

    if len(files) == 0:
        continue

    for fname in files:
        is_dir = os.path.isdir(fname)

        # fix the name
        (dir_part, name_part) = os.path.split(fname)
        (name_part, extension) = os.path.splitext(name_part)
        extension = extension.lower()
        name_part = split_words(name_part, '_', True) + extension
        final_path = os.path.join(dir_part, name_part)

        # is the final name the same as the input value? If so, skip the rest.
        if fname == final_path:
            continue

        # check to make sure the destination doesn't exist yet.
        if (os.path.exists(final_path) and not os.path.samefile(fname,
            final_path)):
            print "Name conflict: %s already exists!" % final_path
            rename_anyway = raw_input("Continue with rename anyway? (y/n): ")
            if rename_anyway.lower() != 'y':
                print "File %s will be unchanged." % fname
                continue

        # rename the file or directory
        print "  %s" % fname
        print "  --> %s\n" % final_path
        os.rename(fname, final_path)

