import re


def readExpFile(fileName,type):
	"""
	This function will read all data from each file, then split it into datasets as an array in data where all datasets have a "name" and its "values"
	The "values" for exp file will be in a 4 column with
		delay, data, data error up, data error down
	and for the fit data will be 2 column with
		delay, data
	"""
	data =[]
	file = open(fileName,'r', encoding='utf8')
	
	allDataFromFile = file.read()
	allRes = allDataFromFile.split("\n\n") # Each dataset is seperated by two linebreaks
	file.close()
	
	for res in allRes:
		currentRes=""
		values=[]
		dataset={}
		for l in res.split("\n"):
			str =l.strip()
			r = re.match(r"\[([A-Za-z0-9_]+)-([A-Za-z0-9_]+)\]",str)
	
			if(r):
				dataset["name"]=r.group(1).strip()
			elif(str.startswith("#")):
				continue
			elif type == "fit":
				dataset["dataexist"]=True
				strList = str.split()
				if len(strList)==3:
					values.append([strList[0],strList[2]])
			elif type == "exp":
				strList = str.split()
				if len(strList)==5:
					values.append([strList[0],strList[2],strList[3],strList[4]])
		dataset["values"]=values
		if len(dataset["values"]) > 0:
			data.append(dataset)

	data_sorted = sorted(data,key=lambda x: x["name"][1:])

	return data_sorted