#!/usr/local/bioinfo/python/2.7.9/bin/python
#
#  Copyright 2014 CIRAD
#
#  This program is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation; either version 3 of the License, or
#  (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program; if not, see <http://www.gnu.org/licenses/> or
#  write to the Free Software Foundation, Inc.,
#  51 Franklin Street, Fifth Floor, Boston,
#  MA 02110-1301, USA.
#
#

import optparse, os, shutil, subprocess, sys, tempfile, fileinput, ConfigParser, operator, time, math

def JMpwd2markid(PWD):
	LISTE = []
	file = open(PWD)
	sur_id = 0
	for line in file:
		data = line.split()
		if data:
			if sur_id:
				LISTE.append(data[1])
			elif data[0] == 'locus' and data[1] == 'numbers:':
				sur_id = 1
	return LISTE

def JMpwd2matrix(PWD, LISTE_ID, OUT1, OUT2):
	#creating the table structure
	# os.system("echo '1)creating the table structure'")
	liste_vide = []
	for n in LISTE_ID:
		liste_vide.append('999999999')
	dic_LOD = {}
	dic_REC = {}
	for n in LISTE_ID:
		dic_LOD[n] = list(liste_vide)
		dic_REC[n] = list(liste_vide)
	
	#filling the table
	# os.system("echo '2)filling the table. It can take time...'")
	file = open(PWD)
	maxlod = 0
	for line in file:
		data = line.split()
		if data != [] and not('name =' in line) and len(data) > 2:
			if data[0] != ';':
				if data[0] in LISTE_ID and  data[1] in LISTE_ID:
					dic_LOD[data[0]][LISTE_ID.index(data[1])] = float(data[3])
					dic_LOD[data[1]][LISTE_ID.index(data[0])] = float(data[3])
					dic_REC[data[0]][LISTE_ID.index(data[1])] = float(data[2])
					dic_REC[data[1]][LISTE_ID.index(data[0])] = float(data[2])
					if maxlod < float(data[3]):
						maxlod = float(data[3])
	file.close()
	
	# filling diag
	# os.system("echo '3)filling diag'")
	for n in LISTE_ID:
		dic_REC[n][LISTE_ID.index(n)] = 0
		dic_LOD[n][LISTE_ID.index(n)] = maxlod
			
	#writing results
	
	# os.system("echo '4)writing results'")
	out1 = open(OUT1,'w')
	out2 = open(OUT2,'w')
	out1.write('ID\t'+'\t'.join(LISTE_ID)+'\n')
	out2.write('ID\t'+'\t'.join(LISTE_ID)+'\n')
	for n in LISTE_ID:
		out1.write(n+'\t'+'\t'.join(map(str,dic_LOD[n]))+'\n')
		out2.write(n+'\t'+'\t'.join(map(str,dic_REC[n]))+'\n')
	out1.close()
	out2.close()

def __main__():
	#Parse Command Line
	parser = optparse.OptionParser(usage="python %prog [options]\n\nProgram designed by Guillaume MARTIN : guillaume.martin@cirad.fr\n\n"
	"This program takes a pairwise file generated by JoinMap (.pwd file in the folder created by joinmap) and returns two matrixes :\n"
	"\t- a matrix containing pairwise LOD score\n"
	"\t- a matrix containing pairwise recombination frequencies")
	# Wrapper options. 
	parser.add_option( '', '--pwd', dest='pwd', default=None, help='The pairwise file calculated by joinmap')
	parser.add_option( '', '--lod', dest='lod', default='lod_matrix.tab', help='The LOD matrix output file name. [default: %default]')
	parser.add_option( '', '--rec', dest='rec', default='rec_matrix.tab', help='The REC matrix output file name. [default: %default]')
	(options, args) = parser.parse_args()
	nom_pairwise = options.pwd
	
	if options.pwd == None:
		sys.exit('Please provide a pairwise Joinmap file in --pwd argument')
	
	#creating a list of marker found in the pairwise file
	# os.system("echo 'creating a list of marker found in the pairwise file'")
	liste_id = JMpwd2markid(nom_pairwise)
		
	# creation of the matrix file
	JMpwd2matrix(nom_pairwise, liste_id, options.lod, options.rec)
	
if __name__ == "__main__": __main__()