import sys,os,math,pprint,time

import ned_commandLine as commandline
import ned_disorderHelper as disorderHelper
import ned_uniprotHelper as uniprotHelper
import ned_stats as stats
import ned_basic as basic
import ned_proteinInfoHelper as proteinInfoHelper
import ned_SLiMPrints as slimprints
import ned_timeUtilities as timeUtilities


import rje_seq,rje_tree,rje_slimcalc

class conservationScorer():
	
	def __init__(self,disorder=None,pfam=None,features=None):
		cmdline = commandline.CommandLine()
		
		self.options = cmdline.loadIniFile(os.path.join(os.path.dirname(os.path.realpath(__file__)),"../settings/utilities.ini"))
		
		self.options["start"] = 0
		self.options["stop"] = 0
		
		self.data = {}
		
		self.runnable = True
		
	def printAlignment(self):	
		self.seqs.querySeq(self.seqs.seq[0].info['AccNum'])
		self.seqs.tidyQueryGaps()
		self.seqs.gapSeqFilter()
		
		self.data["alignment"] = {}
		sequence = self.seqs.seq[0].info['Sequence']
		print
		for i in range(0,len(sequence)):
			self.data["alignment"][i] = {"column":[]}
			for seq in self.seqs.seq:
				self.data["alignment"][i]["column"].append(seq.info['Sequence'][i])
				
		for protein in range(0,len(self.data["alignment"][0]["column"])):
			for residue in range(150,170):
				print self.data["alignment"][residue]["column"][protein],
			print
		
	def findInsertions(self):
		
		aaCount = 0
		gappedCount = 0
		last = 0
		gaps = {}
		self.data["insertion"] = {}
		self.data["insertionLengths"] = {}
		
		for aa in self.seqs.seq[0].info["Sequence"]:
			gappedCount += 1
		
			if aa == "-":
				pass
			else:
				
				if gappedCount - last != 0:
					gaps[aaCount] = (last -1,gappedCount - 1)
					self.data["insertion"][aaCount] = 0
					self.data["insertionLengths"][aaCount] = {}
					
				last = gappedCount + 1
				aaCount += 1
			
			#print aa,gappedCount,aaCount
			
		
		for seq in self.seqs.seq:
			seq.dict["deletionMapperDict"] = {}
			order = gaps.keys()
			order.sort()
			for gap in order:
				start = gaps[gap][0]
				end = gaps[gap][1]
				
				gapSeq = seq.info["Sequence"][start:end]
				#print gap,gapSeq,len(gapSeq) - gapSeq.count("-")
				seq.dict["deletionMapperDict"][gap] = len(gapSeq) - gapSeq.count("-")
				
				self.data["insertion"][gap] = max(self.data["insertion"][gap], seq.dict["deletionMapperDict"][gap] )
				self.data["insertionLengths"][gap][seq.info["AccNum"]] = seq.dict["deletionMapperDict"][gap]
			

		
	def scoreAlignment(self,alignment,disorder=None,pfam=None,features=None,makeFile=False,readFile=False):
	
		runScorer = True
		self.options["alignment"] = alignment
		self.options["scoresPath"] =  self.options["alignment"] + ".scores"

		self.seqs = rje_seq.SeqList(log=None,cmd_list=['maxgap=0.2','maxx=0.2','gapfilter=T','v=-1','i=-1', 'iuchdir=T','relcons=T',"iucut=0.2","iumethod=short",'replacechar=F','stripnum=F',"iupath=" + self.options["iupath"] ])
		self.seqs.loadSeqs(seqfile=self.options["alignment"])
		self.seqs.querySeq(self.seqs.seq[0].info['AccNum'])
		self.seqs.gapSeqFilter()

		self.findInsertions()

		self.seqs.tidyQueryGaps()
	

		self.data["Alignment_Degapped"] = {}
		for seq in self.seqs.seq:
			self.data["Alignment_Degapped"][seq.info["AccNum"]] = seq.info["Sequence"]


		if makeFile == True:
			runScorer = True
		else:
			runScorer = False
		
		
		if readFile == True:
			if os.path.exists(self.options["scoresPath"]):
				if basic.fileAgeDays(self.options["scoresPath"]) < 120:
					
					#print "Reading precalculated conservation scores"
					for line in open(self.options["scoresPath"]).read().strip().split("\n"):
					
						bits = line.split("\t")
						if bits[0] in ["ABV","ABS","WCS","WCS_W_r","WCS_W_rStdev","WCS_W_p","Disorder","gapPercent"]:
							self.data[bits[0]] = [float(x) for x in bits[1].split(",")]
						elif bits[0] in ["ignoreList"]:
							self.data[bits[0]] =  bits[1].split(",")
						else:
							self.data[bits[0]] = bits[1]
						
					proteinInfo = proteinInfoHelper.proteinInfoHelper()
					proteinInfo.getInfo(self.data["Acc"],tasks=["fasta","uniprot","disorder","pfam"])
					self.data.update(proteinInfo.data)
			
					if "SpeciesCount" not in self.data:
						if 'Species' in self.data:
							self.data["SpeciesCount"] = self.data['Species']
						
					runScorer = False
				else:
				    print "Conservation data is old. Recalculating....."
			else:
				runScorer = True
		else:
			runScorer = True
					 
					 
		#runScorer = True 
		if runScorer == True:
			print "Running conservation"
		    
			self.seqs = rje_seq.SeqList(log=None,cmd_list=['maxgap=0.2','maxx=0.2','gapfilter=T','v=-1','i=-1', 'iuchdir=T','relcons=T',"iucut=0.2","iumethod=short",'replacechar=F','stripnum=F',"iupath=" + self.options["iupath"] ])
			self.seqs.loadSeqs(seqfile=self.options["alignment"])
			
			self.seqs.querySeq(self.seqs.seq[0].info['AccNum'])
			self.data["Acc"] = self.seqs.seq[0].info['AccNum']
			self.data["Sequence"] = self.seqs.seq[0].info['Sequence'].replace("-","")
			
			self.data["gapPercent"] = []
			
			self.data["proteinListOrdered"] = []
			self.data["gaps"] = 0
			self.data["residues"] = 0
			
			if int(self.options['stop']) == 0 or self.options['stop'] > len(self.data["Sequence"]):
				self.options['stop'] = len(self.data["Sequence"])
			
			if int(self.options['start']) == 0:
				self.options['start'] = 1
			
			self.data["alignment"] = {}
			
			#Degap the alignement relative to the query alignment
			self.seqs.tidyQueryGaps()
			self.seqs.gapSeqFilter()
			self.seqs.reFormat(self.options["alignment"] + ".clustalin","fasta")
			
			self.data["SpeciesCount"] = len(self.seqs.seq)
			
			for i in range(self.options['start'] - 1,self.options['stop']):
				self.data["alignment"][i] = {"column":[]}
				for seq in self.seqs.seq:
					self.data["alignment"][i]["column"].append(seq.info['Sequence'][i])
			
					
			for i in range(self.options['start'] - 1,self.options['stop']):
				for seq in self.seqs.seq:
					if i == self.options['start'] - 1:
						self.data["proteinListOrdered"].append(seq.info['AccNum'])
				
				
					if seq.info['Sequence'][i] == "-" or seq.info['Sequence'][i] == "X":
						self.data["gaps"] += 1
					else:
						self.data["residues"] += 1
						
						
			
			if self.data["SpeciesCount"] < self.options["MinSpec"]:
				print "Not enough sequences within parameters. \t",self.data["SpeciesCount"] , self.options["MinSpec"],
				self.runnable = False
				
			############################
			#Take care of disorder needs
			############################
			
			if disorder == None:
				disScorer = disorderHelper.disorderScorer()
				self.data["Disorder"] = disScorer.disorderFromSequence(self.data["Sequence"])
			else:
				self.data["Disorder"] = disorder.data['ResidueDisorder']
			
			
			slimcalc = rje_slimcalc.SLiMCalc(self.seqs.log,self.seqs.cmd_list+['conspec=', 'slimcalc=', 'vnematrix=BLOSUM62', 'relgappen=T'])
			#print "\n"  +self.data["Sequence"]
			#calulate the primary conservationscores
			self.data["ABS"] = self.seqs.relConList(0)
			self.data["ABV"] = self.seqs.relConList(0,slimcalc)
			
			proteinInfo = proteinInfoHelper.proteinInfoHelper()
			
			proteinInfo.getInfo(self.data["Acc"],tasks=["fasta","uniprot","disorder","pfam","mask"])
		
			self.data.update(proteinInfo.data)
			#print len(self.data["ABS"])
			#print len(self.data["ABV"])
			#print "\n"  + self.data["Sequence"]
			
			seqPos = -1
			for i in range(0,len(self.data["alignment"])):
				if self.data["alignment"][i]["column"][0] != "-":
					seqPos += 1
				
					
				if float(self.data["alignment"][i]["column"].count("-"))/len(self.data["alignment"][i]["column"]) > 0.25:
					if self.data["alignment"][i]["column"][0] != "-":
						try:
							self.data["ignoreList"][seqPos] = "Gappy"
						except:
							print "Error ignoreList - length overflow",len(self.data["alignment"]),seqPos,len(self.data["ignoreList"])
							
				self.data["gapPercent"].append(float(self.data["alignment"][i]["column"].count("-"))/len(self.data["alignment"][i]["column"]))
				
				#print "".join(self.data["alignment"][i]["column"]),float(self.data["alignment"][i]["column"].count("-")),len(self.data["alignment"][i]["column"])
				#print i,"\t",self.data["Sequence"][i],self.data["ignoreList"][i]
			
			
			for i in range(0,len(self.data["Sequence"])):
				window_Length  = len(self.data["ignoreList"][i - 15:i+15])
				
				if self.data["ignoreList"][i - 15:i+15].count("") < float(window_Length)/3:
					if self.data["ignoreList"][i] == "":
						self.data["ignoreList"][i] = "Short"
				
			if self.runnable == True:
				try:
					self.weightColumnScores()
				except Exception, e:
					self.data["WCS"] = [0]*len(self.data["ABV"])
					#self.data["AWCS"] = [0]*len(self.data["ABV"])
					print "Error",e
					
			if self.runnable == True:
				self.calculateRLCscores()
			
			
			if makeFile == True:
				if "WCS" not in self.data:
					self.data["WCS"] = [0]*len(self.data["Sequence"])
				
				if "WCS_W_rStdev" not in self.data:
					self.data["WCS_W_rStdev"] = [0]*len(self.data["Sequence"])
					
				if "WCS_W_p" not in self.data:
					self.data["WCS_W_p"] = [1]*len(self.data["Sequence"])
					
				if "WCS_W_r" not in self.data:
					self.data["WCS_W_r"] = [0]*len(self.data["Sequence"])
					
				
				consStr = ""
				
				for val in ["Sequence","Acc","ABV","ABS","WCS","WCS_W_r","WCS_W_rStdev","WCS_W_p","Disorder","SpeciesCount","ignoreList","gaps","gapPercent",'residues']:
					if val in ["ignoreList"]:
						consStr += val + "\t" + ",".join(self.data[val]) + "\n"
					elif isinstance(self.data[val], list):
						consStr += val + "\t" + ",".join(["%1.4f"%x for x in self.data[val]]) + "\n"
					else:
						consStr += val + "\t" + str(self.data[val]) + "\n"
			
				
				open(self.options["scoresPath"],"w").write(consStr)
			
			#basic.plotList(self.data["WCS_W_p"])
			
				
	def calculateRLCscores(self):
		########
		scoreTypes = ["WCS"]#,"ABV","AWCS"]
		
		for scoreType in scoreTypes:
			########
			self.data[scoreType + "_r"] = []
			self.data[scoreType + "_p"] = []
			self.data[scoreType + "_scores"] = {}
			
			self.data[scoreType + "_W_r"] = []
			self.data[scoreType + "_disorderWeights"] = []
			self.data[scoreType + "_W_p"] = []
			
			for i in range(0,len(self.data["Sequence"])):
				self.start = i - int(self.options["window"])
				self.end = i + int(self.options["window"])
				
				self.data[scoreType + "_scores"][i] = []
				
				windowScore = []
				weights = []
				column = []
				tmp = []
				
				if self.start < 0:
					self.start = 0
				if self.end + 1 > len(self.data["Sequence"]):
					self.end = len(self.data["Sequence"]) - 1
			
				for j in range(self.start,self.end + 1):
					if j == i:
						pass
					else:
						if float(self.data["ABV"][j])/self.data["ABS"][j] > 0.75:
							if (self.data["Disorder"][j] - self.data["Disorder"][i]) < 0:
								w = 2
							else:
								w = 1
								
							weight = (1 - (abs(self.data["Disorder"][j] - self.data["Disorder"][i])**w)**float(self.options["dis_weight"]))
					
							windowScore.append(self.data[scoreType][j]*(weight))
							weights.append(weight)
							tmp.append(self.data["Disorder"][j])
							
							if i not in self.data["ignoreList"]:
								if j  not in self.data["ignoreList"]:
									self.data[scoreType + "_scores"][i].append(self.data[scoreType][j]) 
						
				
				if  len(weights) == 0:
					self.data[scoreType + "_W_r"].append(0)
					self.data[scoreType + "_r"].append(0)
									
					self.data["ignoreList"][i] = "Gappy"
					
				else:
					if len(weights) < 10:
						self.data[scoreType + "_W_r"].append(0)
						self.data[scoreType + "_r"].append(0)
						self.data[scoreType + "_disorderWeights"].append(sum(windowScore)/sum(weights))
						self.data["ignoreList"][i] = "Gappy"
							
					else:
						
						self.data[scoreType + "_W_r"].append(self.data[scoreType][i] - sum(windowScore)/sum(weights))
						
						try:
							self.data[scoreType + "_r"].append(self.data[scoreType][i]  - sum(self.data[scoreType + "_scores"][i])/len(self.data[scoreType + "_scores"][i]))
						except:
							self.data[scoreType + "_r"].append(0)
							
						self.data[scoreType + "_disorderWeights"].append(sum(weights)/len(weights))
						
			self.data[scoreType + "_W_rStdev"] = []
			self.data[scoreType + "_rStdev"] = []
			
			
			for i in range(0,len(self.data["Sequence"])):
				self.start = i - int(self.options["window"])
				self.end = i + int(self.options["window"])
				
				if self.start < 0:
					self.start = 0
				if self.end + 1 > len(self.data["Sequence"]):
					self.end = len(self.data["Sequence"]) - 1
					
				stdev_W_r = stats.std_dev(self.data[scoreType + "_W_r"][self.start:self.end])
				stdev_r = stats.std_dev(self.data[scoreType + "_r"][self.start:self.end])
			
				if stdev_r == 0:
					self.data[scoreType + "_rStdev"].append(0)
					self.data[scoreType + "_p"].append(1)
				else:
					if self.data[scoreType + "_r"] == -1:
						self.data[scoreType + "_rStdev"].append(-10)
						self.data[scoreType + "_p"].append(1)
					else:
						std_r = self.data[scoreType + "_r"][i]/stdev_r
						
						if stdev_r < 0.01:
							self.data["ignoreList"][i] = "NOVAR"
							std_r = 0

						self.data[scoreType + "_rStdev"].append(std_r)
						self.data[scoreType + "_p"].append(max(0.0001,stats.rlcProb(std_r,0,1)))
				
				if stdev_W_r == 0:
					self.data[scoreType + "_W_rStdev"].append(0)
					self.data[scoreType + "_W_p"].append(1)
				else:
					if self.data[scoreType + "_W_r"] == -1:
						self.data[scoreType + "_W_rStdev"].append(-10)
						self.data[scoreType + "_W_p"].append(1)
					else:
						std_wr = self.data[scoreType + "_W_r"][i]/stdev_W_r
						
						
						if stdev_W_r < 0.01:
							self.data["ignoreList"][i] = "NOVAR"
							std_wr = 0

						self.data[scoreType + "_W_rStdev"].append(std_wr)
						self.data[scoreType + "_W_p"].append(max(0.0001,stats.rlcProb(std_wr,0,1)))
					
		 
	def calculateWeights(self):
		
		self.weights = {}
		self.removeList = []
		
		maxBranchLength = 1.0
		
		root_path = os.path.abspath(self.options['alignment']).split(".")[0] + ".root"
		open(root_path,"w").write(self.seqs.seq[0].info['Name'] + "\n")
	
		accnum = self.seqs.seq[0].info['AccNum']
		quietness = -1
		
		if self.options["quiet"] == "F":
			quietness = 1
	
			
		if len(self.options["clustalw"]) > 0:
			alignmentAlgorithm = "clustalw=" + self.options["clustalw"]
			useAlgorithm = 'maketree=clustalw'
			
		elif len(self.options["FastTree"]) > 0:
			alignmentAlgorithm = "fasttree=" + self.options["FastTree"]
			useAlgorithm = 'maketree=fasttree'
			
		cmds = [
		'v=' + str(quietness),
		"seqin=" + os.path.abspath(self.options['alignment'] + ".clustalin"),
		"root=" + root_path,
		alignmentAlgorithm,
		"basefile="+ os.path.abspath(self.options['alignment']).split(".")[0],
		"resdir="+ os.path.abspath(self.options['alignment']).split(".")[0],
		useAlgorithm,
		"clustalw=" + self.options["clustalw"],
		"i=-1"]
		
		
		try:
			
			try:
				tree = rje_tree.Tree(log=None, cmd_list=cmds)
				tree.textTree()
			except ValueError:
				print "Error making Tree"
	
			os.remove(os.path.basename(self.options['alignment']) + ".phb")
			
			tips = {}
			above = {}
			map = {}
			map_reverse = {}
			root = ""
			
			for node in tree.node:
				try:
					if node.info["Type"] == 'Internal':
						surround = [int(x) for x in node.info['Name'].split("(")[1][:-1].split(",")]
						surround.sort()
						surround = [str(x) for x in surround]
						
						if len(surround) > 2:
							down = surround[:2]
							up = surround[-1]
							
							above[str(node.stat["ID"])] = above[down[0]] + above[down[1]]
							
							if down[0] not in above[str(node.stat["ID"])]:
								above[str(node.stat["ID"])].append(down[0])
							if down[1] not in above[str(node.stat["ID"])]:
								above[str(node.stat["ID"])].append(down[1])	
								
					elif node.info["Type"] == 'Terminal':
						map[node.info["Name"].split()[0]] = node.stat["ID"]
						map_reverse[node.stat["ID"]] = node.info["Name"].split()[0]
						
						above[str(node.stat["ID"])] = [str(node.stat["ID"])]
					elif node.info["Type"] == 'Root':
						root = str(node.stat["ID"])
						
						surround = [int(x) for x in node.info['Name'].split("(")[2][:-1].split(",")]
						surround.sort()
						surround = [str(x) for x in surround]
						down = surround[:2]
						
						above[str(node.stat["ID"])] = above[down[0]] + above[down[1]]
						
						if down[0] not in above[str(node.stat["ID"])]:
							above[str(node.stat["ID"])].append(down[0])
						if down[1] not in above[str(node.stat["ID"])]:
							above[str(node.stat["ID"])].append(down[1])	
						
				except Exception,e:
					raise
			
			lengths = {}
			for branch in tree.branch:
				
				try:	
					length = branch.stat["Length"]
					bits =  branch.info["Name"].split()
					
					if len(bits) == 3:
						node1 = "1"
						node2 = str(max([int(x) for x in bits[1][1:-1].split(",")]))
					elif bits[2] == "Root" and bits.count("Node") == 1:
						node1 = str(bits[4])
						node2 = str(map[bits[7]])
					elif bits[2] == "Root" and bits.count("Node") == 2:
						node1 = str(bits[4])
						node2 = str(bits[8])
					elif bits.count("Node") == 2:
						node1 = str(bits[1])
						node2 = str(bits[5])
					else:
						node1 = str(bits[1])
						node2 = str(map[bits[4]])
						
					if node1 in lengths:
							lengths[node1][node2] = length
					else:
							lengths[node1] = {}
							lengths[node1][node2] = length
						
					if node2 in lengths:
							lengths[node2][node1] = length
					else:
							lengths[node2] = {}
							lengths[node2][node1] = length
					
				except Exception,e:
					raise
		
			
			path = {}
			for node in above:
				sorter = [int(x) for x in above[node]]
				sorter.sort()
				for val in sorter:
					if str(val) in path:
						path[str(val)].append(node)
					else:
						path[str(val)] = [node]
				
		
			sortedNodes = [int(x) for x in above.keys()]
			sortedNodes.sort()
			
			fromRoot = {}
	
			self.weights[map_reverse[int(sortedNodes[0])]] = 0.0
			
			for val in sortedNodes[1:]:
			
				longBranch = False
				val = str(val)
		
				if val != root:
					try:
						if int(val) in map_reverse:
							
							sortedPath = [int(x) for x in path[val]]
							sortedPath.sort()
							
							last = str(val)
							l = 0
							prof = 0
							count = 0
							
							
							for v in sortedPath  + [1]:
							
								v = str(v)
								
								if last == v:
									pass
								else:
									if v in lengths:
										l += float(lengths[v][last])
										if float(lengths[v][last]) > maxBranchLength:
											longBranch = True
											
										prof += float(lengths[v][last])/(len(above[last])) #len(sortedPath) - 
									else:	
										pass
									
								last = v
								count += 1
							
							fromRoot[map_reverse[int(val)]] = l
							
							w = prof + (lengths[str(root)][str(1)]/(len(above) - 1))
							
							if self.options["prune_long"] == "T" and longBranch == True:
								if self.options["quiet"] == "F":
									print "Pruning branch" + map_reverse[int(val)]
									
								self.removeList.append(map_reverse[int(val)])
							else:
								self.weights[map_reverse[int(val)]] = w
								
					except Exception,e:
						raise
						
			
			os.remove(root_path)
		except Exception,e:
			print "Errot: Tree making was banjaxed",e
			pass		
			
			
	def weightColumnScores(self):
		try:
			self.calculateWeights()
			
			
			if len(self.removeList) > 0:
				print "Remove list:",self.removeList
			
			count = 0
			removeMe = []
			for seq in self.seqs.seq:
				count += 1
				
				#print seq.info["ID"] + "__" + seq.info['AccNum'] 
				if seq.info["Name"].split()[0] in self.removeList:
					
					#if self.options["quiet"] == "F":
					print "Removing:", seq.info["ID"] + "__" + seq.info['AccNum']
						
						
					removeMe.append(seq)
				
			for rem in removeMe:
				try:
					self.seqs.seq.remove(rem)
				except Exception, e:
					print e
					
			if len(self.seqs.seq) < self.options["MinSpec"]:
				if self.removeList > 1:
					print "Divergence too large. \t",
				else:
					print "Not enough sequences within parameters (" + str(len(self.seqs.seq)) + ")",
					
				self.data["WCS"] = [0]*len(self.data["Sequence"])
				self.data["AWCS"] = [0]*len(self.data["Sequence"])
				
				#self.runnable = False
				
			else:
				self.data["WCS"] = []
				self.data["AWCS"] = []
				query = self.seqs.seq[0].info["Sequence"]
				length = len(self.seqs.seq[0].info["Sequence"])
	
				weight = sum(self.weights.values())
				
				
				ambGroups = ["AGS","ILMV","FYW","KRH","DE","ST"]
					
				for i in range(0,length):
					
					summer = 0
					ambsummer = 0
					
					ambGroup = [self.seqs.seq[0].info["Sequence"][i]]
					for ambGroupTmp in ambGroups:
						if self.seqs.seq[0].info["Sequence"][i] in ambGroupTmp:
							ambGroup.append(ambGroupTmp)
					
					for seq in self.seqs.seq:
						
						if seq.info["Sequence"][i] == query[i]:
							summer += self.weights[seq.info['Name'].split()[0]]
							ambsummer += self.weights[seq.info['Name'].split()[0]]
						
						elif ([seq.info["Sequence"][i] in x for x in ambGroup]).count(True) > 0:
							ambsummer += self.weights[seq.info['Name'].split()[0]]*(1 + math.log((1.0/len(max(ambGroup, key=len))),20))
						
					if summer == 0.0 or weight == 0.0:
						self.data["WCS"].append(0.0)
						self.data["AWCS"].append(0.0)
					else:
						self.data["WCS"].append(summer/weight)
						self.data["AWCS"].append(ambsummer/weight)

		except Exception,e:
			print "Error in weighting scheme",e
			basic.writeError(e)
				
	def createSLIMPrintsStyleOutput(self):
		output = ""
		###########
		#Create Header
		###########
		if self.options["server"] == "F":
			
			output += "Pos\t"
			output += "Column" + " "*(len(self.data["alignment"][i]["column"]) - 6) + "\t"
			output += "|Dis\t"
			
			#output += "|ABV\t"
			
			if self.options["weighted"] == "T":
				output += "WCS\t"
				#output += "AWCS\t"
				
				
			#output += "|ABV_r\t"#VNE_r\t"
			
			if self.options["weighted"] == "T":
				output += "WCS_r\t"#AWCS_r\t"
				
			#output += "ABV_Wr\t"#VNE_r\t"
			
			if self.options["weighted"] == "T":
				output += "WCS_Wr\t"#AWCS_Wr\t"
		
			output += "WCS_Dp\t"#"|ABV_Dp\tAWCS_Dp\t|"	
		
			#for score in ["ABV"]:
			#	output += score + "_p\t" 
				
			if self.options["weighted"] == "T":
				output += "WCS_p\t"#AWCS_p\t"
			
			output += "|Mask\t|Graph\n"
				
		graph = self.data["translate"][self.options["scoreWeight"]]
		
		###########
		#Create data output
		###########
		
		for i in range(self.options['start']  - 1,self.options['stop']):
			output += str(i+1)
			
			if self.options["server"] == "T":
				output += "\t" + self.seqs.seq[0].info['AccNum']
				output += "\t" + str(len(self.seqs.seq))
				
			###################
			output += "\t" + "".join(self.data["alignment"][i]["column"])
			###################
			output += "\t|%1.4f"%self.data["Disorder"][i] 
				###################
			#output += "\t|%1.3f"%self.data["ABS"][i]
			#output += "\t|%1.4f"%self.data["ABV"][i]
			
			if self.options["weighted"] == "T":
				output += "\t%1.4f"%self.data["WCS"][i] 
				#output += "\t%1.4f"%self.data["AWCS"][i] 
			###################
			#output += "\t|%1.3f"%self.data["ABV_rStdev"][i]
			if self.options["weighted"] == "T":
				output += "\t%1.3f"%self.data["WCS_rStdev"][i]
				#output += "\t%1.3f"%self.data["AWCS_rStdev"][i]
				
			#output += "\t|%1.3f"%self.data["ABV_W_rStdev"][i]
			
			if self.options["weighted"] == "T":
				output += "\t%1.3f"%self.data["WCS_W_rStdev"][i]
				#output += "\t%1.3f"%self.data["AWCS_W_rStdev"][i]
		
			###################
			#output += "\t|%1.4f"%self.data["ABV_W_p"][i]
			if self.options["weighted"] == "T":
				output += "\t%1.4f"%self.data["WCS_W_p"][i] 
				#output += "\t%1.4f"%self.data["AWCS_W_p"][i] 
			###################
			#output += "\t|%1.4f"%self.data["ABV_p"][i] 
			if self.options["weighted"] == "T":
				output += "\t%1.4f"%self.data["WCS_p"][i] 
				#output += "\t%1.4f"%self.data["AWCS_p"][i] 
			###################
			output += "\t|"  +self.data["ignoreList"][i]
			
			###################
			output += "\t|%1.4f"%self.data[graph][i] 
			###################
			try:
				output += "\t|" + "*"*int(abs(math.log((self.data[graph][i] ),2)))
			except:
				output +=  "\t|" + "Error:" + str(self.data[graph][i])
			
				
			output += "\n"
		
		if self.options["quiet"] == "F" and self.options["rlcScorer"] == "F":
			print "\n" + output.strip()
			print "-"*140
			
		open(outputPath,"w").write(output.replace("|",""))
		
if __name__ == "__main__":
	try:
		####################################
		#accession = sys.argv[1]
		
		#conHelper = conservationScorer()
		
		#alignmentDir = conHelper.options['alignment_dir']
		#alignmentPath = os.path.join(alignmentDir,"ALN",accession + ".orthaln.fas")
		
		#print alignmentPath
		#proteinInfo = proteinInfoHelper.proteinInfoHelper()
		#proteinInfo.getInfo("P04637",tasks=["alignment"])
		alignmentPath = sys.argv[1]
		
		conHelper = conservationScorer()
		conHelper.scoreAlignment(alignmentPath)
		
		slimprintsHelper = slimprints.SLiMPrints()
		slimprintsHelper.data.update(conHelper.data)
		
		try:
			slimprintsHelper.initialiseData()
		except Exception,e:
			print "Error initialising data",e
			sys.exit()
		
		slimprintsHelper.createMotifs()
		slimprintsHelper.findChildren()
		slimprintsHelper.compressMotifs()
		slimprintsHelper.createCompressedOutput()
		slimprintsHelper.createFlatOutput()


		#print open(os.path.join(os.path.dirname(options["alignment"]),os.path.basename(options["alignment"]).split(".")[0] + "_comp_SLiMPrints.out"),"r").read()
	
											
	except Exception,e:
		basic.writeError(e)
		raise
	