#! /usr/bin/env python 
###################################
#    Davi Ortega 8/13/2012 
###################################

import sys
import numpy
if '-h' in sys.argv:
	print 'Read something like: \nname1 name1 value11\nname1 name2 value12\n name2 name1 value21\n...\n and put in the matrix format with first row as headers... compatible to MDS_3D\nOption -fd0 Force diagonal to be zero\n -D for 1/(value) \n -sep "#"  \tWhere # is the separator of data'
	sys.exit()

if '-sep' in sys.argv:
	sep = sys.argv[sys.argv.index('-sep') + 1]

if '-D' in sys.argv:
	outfilename = sys.argv[1][:-3] + 'D.matrix.txt'
else:
	outfilename = sys.argv[1][:-3] + 'matrix.txt'

print sep
datafile = open(sys.argv[1],'r')

names = []
data_dic = {}
values = []

for line in datafile:
	fields = line.replace('\n','').split('\t')
	if fields[0] not in names:
		names.append(fields[0])
	if fields[0] not in data_dic.keys():
		data_dic[fields[0]] = {}
	if '-D' not in sys.argv:
		if fields[1] not in data_dic[fields[0]].keys():
			data_dic[fields[0]][fields[1]] = fields[2]
		elif fields[2] < data_dic[fields[0]][fields[1]]:
			data_dic[fields[0]][fields[1]] = fields[2]
		values.append(float(fields[2]))
	else:
		if fields[1] not in data_dic[fields[0]].keys():
                        data_dic[fields[0]][fields[1]] = 1/float(fields[2])
                elif fields[2] > data_dic[fields[0]][fields[1]]:
                        data_dic[fields[0]][fields[1]] = 1/float(fields[2])
		values.append(1/float(fields[2]))

values = numpy.array(values)

datafile.close()

output = ''
for name in names:
	print str(len(data_dic[name].keys())) + sep + name

errors = 0

for name1 in names:
	output += name1
	for name2 in names:
		if '-fd0' in sys.argv:
			if name1 == name2:
				output += sep + '0.0'
			else:
				#print name1 +'\t'+name2
				try:
					output += sep + "%.3f" % data_dic[name1][name2]
				except KeyError:
					#print name1 + sep +name2
					
					#insert max here
					output += sep + "%.3f" % (max(values))
					errors += 1
		else:
			try:
				output += sep + "%.3f" % data_dic[name1][name2]
			except KeyError:
				#print name1 + sep +name2
				output += sep + "%.3f" % (max(values))
				errors += 1

			
	output += '\n'
print 'Missing values = ' + str(errors)


outfile = open(outfilename, 'w')
outfile.write(output)
outfile.close()

		
			



