import os,sys
import ned_basic as basic

def readTableFile(tablePath,delimiter="\t",hasHeader=True,key="",byColumn=True,relationship="binary",stripQuotes=False):
	if os.path.exists(tablePath):
		rows = open(tablePath).read()
		if stripQuotes:
			rows = rows.replace('"',"")
			
	
		rows = rows.replace("\r","\n").strip("\n").strip("\r")
		rows = rows.split("\n")
		
		start_row = 0
		while (rows[start_row][0:2] == "##"):
			start_row += 1
		
		
		if hasHeader:
			headers = rows[start_row].split(delimiter)
			start_row += 1
		else:
			headers = range(0,len(rows[0].split(delimiter)))
			
		tableData = {}
		
		if key == "":
			if byColumn == True:
				for header in headers:
					tableData[header] = []
		else:
			if key not in headers:
				print "Key not in header"
				return
			
			keyIndex = headers.index(key)
			
		for row in rows[start_row:]:
			try:
				if len(row) > 0:
					bits = row.split(delimiter)
					
					if byColumn == True:
						if key == "":
							for i in range(0,len(headers)):
								tableData[headers[i]].append(bits[i])
						else:
							tableData[bits[keyIndex]] = {}
							for i in range(0,len(headers)):
								if key != headers[i]:
									tableData[bits[keyIndex]][headers[i]] = bits[i]
					else:
						if key == "":
							tableData[len(tableData)] = {}
							for i in range(0,len(headers)):
								tableData[len(tableData) -1][headers[i]] = bits[i]
						else:
							if relationship == "binary":
								tableData[bits[keyIndex]] = {}
							else:
								if bits[keyIndex] not in tableData:
									tableData[bits[keyIndex]] = []
									
								tableDataTmp = {}
							
								
								
							for i in range(0,len(headers)):
								if key != headers[i]:
									if relationship == "binary":
										tableData[bits[keyIndex]][headers[i]] = bits[i]
									else:
										tableDataTmp[headers[i]] = bits[i]
	
							if relationship != "binary":
								tableData[bits[keyIndex]].append(tableDataTmp)
								
			except:
				raise
				print "Skipping",row
				
		return tableData
	else:
		print "File not found:" + tablePath

	
if __name__ == "__main__":
	table = sys.argv[1]
	
	readTableFile(table,key='elminstanceid')
	
	tableData = readTableFile(table)

	print len(basic.removeRedundency(tableData['uniprotid']))
	print basic.removeRedundency(tableData['uniprotid'])