#!/usr/bin/env python

# Not DONE

#
# Read in the command line list of files and output each 
# formatted file according to -X.
#
# David Edwards  <davidbtdt@gmail.com> Mon Jan  2 14:02:33 PST 2012
# Fri Aug 17 18:24:46 PDT 2012: Added -f option
# Sun Oct 21 14:59:33 PDT 2012: Added -r option

import sys
import os
import re

help = """
David Edwards  <davidbtdt@gmail.com> Aug 17 2012
Python 3 script

fmt_fnames - By default, rename files that contain spaces to use
underscores instead. Other formatting can be specified with an option.

Usage:  fmt_fnames [-X] file(s)

where
     -X can be one of the following:

         -f    Same as -_ except delete spaces around "-" and "_" (default)
         -_    Replace all spaces with underscores
         --    Replace all spaces with dashes
         -c    Capitalize each word
         -l    Convert the line to all lower case
         -u    Convert the line to all upper case
         -s    Replace all underscores with spaces
         -d    Replace all dashes with spaces
		 -r x y Replace string "x" with "y"  

     "file(s)" is one or more file names that can contain wild cards.

This works on subdirectory names as well as regular files.

File extensions are always converted to lower case. Dot files are
not treated as an extension.

Example:  fmt_fnames *.wav
  God Rules.wav --> God_Rules.wav
  MX1 - 2012  Speed _Rd7.MPG --> MX1-2012_Speed_Rd7.mpg"
  Fred_Flin-_-Stoned --> Fred_Flin-Stoned

Example: fmt_fnames -u .Fred.JPG .barney
	.FRED.jpg .BARNEY
"""

if len(sys.argv) < 2:
	print(help)
	exit(1)			# See: http://docs.python.org/py3k/library/sys.html#sys.exit

# Process the command line arguments
opt = sys.argv[1]
i = 2

actions = { \
'-f': 'name.replace(" ", "_")', \
'-c': 'name.title()', \
'-u': 'name.upper()', \
'-l': 'name.lower()', \
'-_': 'name.replace(" ", "_")', \
'--': 'name.replace(" ", "-")', \
'-s': 'name.replace("_", " ")', \
'-d': 'name.replace("-", " ")', \
'-r': 'name.replace(sys.argv[2], sys.argv[3])'}

if opt not in actions:
	opt = '-f'
	i=1

if opt == '-r':
	i=4

for path_name in sys.argv[i:]:
	if os.path.exists(path_name):

		i_slash = path_name.rfind('/')
		if i_slash == -1:
			base_name = ''
			name = path_name
		else:
			i_slash += 1
			base_name = path_name[:i_slash]
			name = path_name[i_slash:]

		#print("NEW NAME: " + path_name)
		#print("-->" + base_name + "<--")
		#print("-->" + name + "<--")

		new = eval(actions[opt])

		# Always change to lower case extensions except dot files
		j = new.rfind('.')
		if j > 0:
			new = new[:j] + new[j:].lower()

		# Further process -f option
		if opt == '-f':
			new = re.sub('_*-_*', '-', new)
			new = re.sub('_+','_', new)
			new = re.sub('-+','-', new)

		if name == new:
			continue

		if os.path.exists(base_name + new):
			print('"'+name+'" not renamed. "'+base_name+new+'" already exists.')
		else:
			print(path_name + ' --> ' + base_name + new)
			os.rename(path_name, base_name + new)
	else:
		print("File not found: " + path_name)

