from __future__ import with_statement
from optparse import OptionParser
import re, os

def main():
	# parse command line
	parser = OptionParser()
	parser.usage = "%prog <input pls file> <output asx file>"

	(options, args) = parser.parse_args()

	if len( args ) != 2:
		parser.error( "source and destination arguments required" )

	# set up variables from command line values
	src = os.path.normpath( args[ 0 ] )
	dst = os.path.normpath( args[ 1 ] )
	
	if src == dst:
		parser.error( "Source and destination file cannot be the same" )

	# create a list of strings, one per line in the source file
	lines = []
	with open( src, "r" ) as f:
		lines = f.readlines()

	# parse lines	
	if lines != None:
		# open the destination for writing
		with open( dst, "w" ) as f:
			for line in lines:
				# search for the URI
				match = re.match( "^[ \\t]*file[0-9]*[ \\t]*=[ \\t]*(.*$)", line, flags=re.IGNORECASE )
				if match != None:
					if match.group( 1 ) != None:
						# URI found, it's saved in the second match group
						# output the URI to the destination file
						print "Found '%s'" % match.group( 1 )
						f.write( match.group( 1 ) )
						f.write( "\n" )
		print "Done writing to '%s'" % dst
	else:
		print "Source file '%s' is empty or does not exist, nothing to do..." % src

if __name__ == "__main__":
    main()
