#!/usr/bin/env python
"""
Flatten deeply included lilypond files
"""

import sys,string,os

def usage():
	print """
Synopsis: %s file

%s dumps file to stdout, expanding `\include "subfile"' to the content
of subfile recursively.
Does not stop anywhere but end of file.

2003 Patrick Atamaniuk
based on lyinclude 
(c)2003 David Raleigh Arnold under GNU.
""" % (sys.argv[0],sys.argv[0])
	return 99


def get_includefilename(line):
	"""
	Look if line is an include statement.
	If it is, look if the file is available, and return its name.
	If it is not available, then it must be a system include (paper1.ly)
	"""

	#ignore comments after include statement, cut line at comment.
	commentpos = string.find(line,'%')
	if commentpos >= 0:
		line = line[:commentpos]	#chop line

	pos = string.find(line, "\\include")
	if pos < 0: return None			#normal line

	includefilename = string.strip(line[pos+9:])[1:-1] #D.R.Arnold
	if os.path.isfile(includefilename): 	#file in cwd and readable?
		return includefilename
	#its not available, assume its a system include and let the line as is
	return None

def parse(infile):
	"""
	dump a file line by line but include recursively.
	"""
	lineno = 0L

	#sys.stderr.write('opening %s\n'%infile)
	print "%%source <%s>" % infile
	fp = open(infile,'r')
	while 1: #while and readline is for large projects more
		 # memory efficient than for x in readlines()
		line = fp.readline()
		if not line: break 	# EOF
		lineno = lineno + 1 	# just for fun and comments
		includefilename = get_includefilename(line)
		if includefilename:
			print "%% %s line %d including %s" % \
				(infile,lineno,includefilename)
			parse(includefilename)
		else:
			sys.stdout.write(line)
	print "%% end of %s" % infile

def main():
	"""
	 i like main(). it hints me where to start reading.
	 but its obviously pretty obsoloete to have on such small scripts.
	"""
	try:
		infile = sys.argv[1]
	except:		#catch all errors (nonexistent file e.g.)
		sys.exit(usage())

	parse(infile)

main()
