#!/usr/bin/python

import getopt, sys, os, re

def extract(filename, dirname, prefix):
	f = open(filename)
	print "Reading %s..." % os.path.basename(filename)
	fcontent = f.read()

	# The MP3 extraction code is stable
	if fcontent.startswith('ID3'):
		print "Extracting MP3 files from %s..." % os.path.basename(filename)
		files = re.findall('ID3.{4,300}(?:SfMarkers|vTYER).+?(?=ID3.{4,300}(?:SfMarkers|vTYER)|$)',fcontent, re.DOTALL)
		suffix = "mp3"
	# The Ogg Vorbis extraction code produces readable, but not quite right files
	elif fcontent.startswith('OggS'):
		print "Extracting Ogg Vorbis files from %s" % os.path.basename(filename)
		files = re.findall('OggS.{4,300}Sony.+?(?=OggS.{4,300}Sony Ogg Vorbis|$)',fcontent, re.DOTALL)
		suffix = "ogg"
	
	for i in range(len(files)):
		outputname = os.path.join(dirname, "%s%02d.%s" % (prefix, i+1, suffix))
		fo = open(outputname, "w")
		print "Writing file %s of %s: %s." % (i+1, len(files), outputname)
		fo.write(files[i])
		fo.close()
		

def usage():
	print "Usage: "+os.path.basename(sys.argv[0])+" FILE [OUTPUTDIR] [OUTPUT FILENAME PREFIX]\nExtract MP3 or Ogg Vorbis files from glm file FILE."

def main():
	try:
		opts, args = getopt.getopt(sys.argv[1:], "h", ["help"])
	except getopt.GetoptError, err:
		# print help information and exit:
		print str(err) # will print something like "option -a not recognized"
		usage()
		sys.exit(2)
	
	output = None
	verbose = False
	for o, a in opts:
		if o in ("-h", "--help"):
			usage()
			sys.exit()
		else:
			assert False, "unhandled option"

	dirname = ""

	if len(args):
		filename = args[0]
		prefix = '.'.join( os.path.basename(filename).split('.')[:-1] ) + "-"
	else:
		usage()
		sys.exit(2)
	if len(args) > 1:
		dirname = args[1]
	if len(args) > 2:
		prefix = args[2]

	extract(filename, dirname, prefix)
    

if __name__ == "__main__":
	main()

