from decrunch import *
import os
import sys
import errno
import imp

# Prompt user for level path
sys.stdout.write("Level pack path (Include trailing slash)> ")
levpath = sys.stdin.readline().strip()

execfile("%stundrize.py" % (levpath))
g.LEMMINGS_PATH = levpath

extracted_levs = []

for packname in datList:
	if packname[-4:].lower() == ".dat":
		extracted_levs.extend(decompressDOSDATString(open("%s%s" % (levpath, packname), "rb").read()))
	elif packname[-4:].lower() == ".lvl":
		extracted_levs.append(open("%s%s" % (levpath, packname), "rb").read())
	else:
		print "Unknown format for level file %s, skiping." % (packname)

pythonated_levs = []
for i, lvl in enumerate(extracted_levs):
	if levelOptions.has_key(i):
		pythonated_levs.append(pythonateDOSLevelString(lvl, author=levelOptions[i][0], ONML=levelOptions[i][1]))
	else:
		pythonated_levs.append(pythonateDOSLevelString(lvl, author=levelOptions["default"][0], ONML=levelOptions["default"][1]))

# Create the directories needed for the levels
for i, difName in enumerate(difNames):
	difpath = "../levels/%s/%d %s/" % (levpackName, i, difName)
	try:
		os.makedirs(difpath)
	except OSError, e:
		if e.errno == errno.EEXIST:
			print "%s already exists." % (difpath)
		else:
			raise

# Finaly, actually extract the darned things!
for i, lev in enumerate(pythonated_levs):
	levelpath = "../levels/%s/%d %s/%d.xml.gz" % (levpackName, i/levsPerDif, difNames[i/levsPerDif], i%levsPerDif)
	print levelpath
	if hasattr(lev, "exportSpecialFlag"): # Wee, special levels!
		print "Special!"
		exportSpecial(lev, levelpath)
		lev.exportXML(levelpath, useGzip=True)
	else:
		print "Non-Special" # You may not be a special level, but we still love you!
		lev.exportXML(levelpath, useGzip=True)

