# -*- coding: utf-8 -*-
"""
MFIL - Blizzard Manifest File
Used for Blizzard Installer

Version 1:
 - Simple dictionary
 - Simple list

Version 2:
 - Dictionary
 - Nested keys
"""

SEEK_CUR = 1

class MFILError(Exception):
	"""
	Generic MFIL exception
	"""
	pass

class MFIL(dict):
	"""
	Dictionary class for Blizzard Manifest Files
	"""
	
	def __init__(self, file):
		file.seek(0)
		self.file = file
		key, value = self.parseKey(), self.parseValue()
		if key == "version":
			self.version = value
		else:
			raise MFILError("Unknown MFIL version")
		
		self.parse()
	
	def parseKey(self):
		ret = []
		while True:
			c = self.file.read(1)
			
			if not c or c == "=":
				break
			
			ret.append(c)
		return "".join(ret)
	
	def parseValue(self):
		ret = []
		while True:
			c = self.file.read(1)
			
			if not c or c == "\n":
				break
			
			if c == "\r":
				if self.file.read(1) == "\n":
					break
				else:
					self.file.seek(-1, SEEK_CUR)
			
			ret.append(c)
		return "".join(ret)

class MFIL2(MFIL):
	"""
	MFIL version 2
	Keys that start with a tab are child keys of the others
	The class should look like MFIL({
		parentKey: {
			parentValue: {
				key: value,
				key2, value2,
			}, ...
		}, ...
	})
	"""
	
	def parse(self):
		while True:
			key, value = self.parseKey(), self.parseValue()
			
			if not key:
				break
			
			elif key.startswith("\t"):
				key = key[1:]
				self[k1][k2][key] = value
			
			else:
				if key not in self:
					self[key] = {}
				self[key][value] = {}
				k1, k2 = key, value

@@ -599,52 +599,151 @@
 %5D%0A%09%09
-while Tru
+self.nextLine = self.file.readline()%0A%09%09for c in self.nextLin
 e:%0A%09%09%09
+if 
 c =
- self.file.read(1)
+= %22=%22:%0A%09%09%09%09self.nextLine = self.nextLine%5Blen(ret)+1:%5D%0A%09%09%09%09break
 %0A%09%09%09%0A%09%09%09
 if n
@@ -734,32 +734,38 @@
 reak%0A%09%09%09%0A%09%09%09
+el
 if 
-not c
+c == %22%5Cr%22
  or c == %22=%22
@@ -758,28 +758,52 @@
 r%22 or c == %22
-=
+%5Cn
 %22:%0A
+%09%09%09%09self.nextLine = %22%22%0A
 %09%09%09%09break%0A%09%09
@@ -885,130 +885,52 @@
 %5D%0A%09%09
-while True:%0A%09%09%09c = self.file.read(1)%0A%09%09%09%0A%09%09%09if not c or c == %22%5Cn%22:%0A%09%09%09%09break%0A%09%09%09%0A%09%09%09if c == %22%5Cr%22:%0A%09%09%09%09if self.file.read(1)
+for c in self.nextLine:%0A%09%09%09if c == %22%5Cr%22 or c
  == 
@@ -943,59 +943,14 @@
 %09%09%09%09
-%09
 break%0A
-%09%09%09%09else:%0A%09%09%09%09%09self.file.seek(-1, SEEK_CUR)%0A
 %09%09%09%0A

Simplify the parsing algo to use readline(), preventing parseKey from having newlines