#!/usr/bin/env  python

import os
import sys
import glob
import re

# main function
def main():
	"""Applies a renaming function to all files in a directory.

The directory is obtained by user input via the console.
"""

	#pat = re.compile( r'^(\d+_)(.+)' )
	#srmvix = lambda str: re.sub( r'^\d+_', '', str)
	#sigml = "012345_thing.sigml"
	#print srmvix( sigml )
	#return

	if __name__ == "__main__":
		dir, junka, junkb = sys.argv[0].rpartition("/")
		os.chdir( dir )
	else:
		dir = os.getcwd()
	print "dir: ", dir

	dfltsdir = 'LSF_IdGlossHns-h-signs'
	print "Stripping initial index numbers from files in a SiGML directory:"
	print 'SiGML directory? (default is {0}) '.format( dfltsdir ),
	sdir = sys.stdin.readline().strip()
	if (sdir == None or len( sdir ) == 0):
		sdir = dfltsdir

	abssdir = "{0}/{1}".format( dir, sdir )

	os.chdir( abssdir )
	print "dir: ", os.getcwd()

	rnfun = getRenameFun()

	for sfl in glob.glob( '*.sigml' ):
		os.rename( sfl, rnfun( sfl ) )
		#print sfl

	os.chdir( ".." )

#----------------

def getRenameFun():
	"""Provides the renaming function for filenames.

In this case the function is the one that removes an initial
numeric index (and underscore) from a name.
"""
	return getStripIndexFun()
	
def getStripIndexFun():
	"""Returns the function that strips an initial numeric index."""

	# If the name has an initial index of the form 'NUM_stuff' the
	# function returns just the 'stuff' part.
	pat = re.compile( r'^(\d+_)?(.+)' )
	return lambda name: pat.match( name ).group( 2 )

#----------------
if __name__ == "__main__":
	main()
#----------------


#---
