#!/usr/bin/python

# See below for name and description
# Copyright (C) 2011 Niall J. Haslam
#  
# 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 2 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, write to 
# the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
#
# To incorporate this module into your own programs, please see GNU Lesser General Public License disclaimer in rje.py

"""
Program:      SLiMPred
Description:  Short Linear Motif Prediction tool
Version:      3.0
Last Edit:    29/11/11
Copyright (C) 2011  Niall J. Haslam - See source code for GNU License Notice
"""

import sys
import os
import subprocess
from subprocess import call
import shutil
import os.path

def SLiMPred(infile, outfile, threshold):
	cmd = "/home/testing/public_html/Bioware_Servers/SLiMpred/SLiMpred.pl", infile, str(threshold), outfile
	subprocess.Popen(cmd).wait()	
	f = open(outfile + ".SLiMpred", 'r')
	
	BioPredArrayResults = f.readlines()
	
	return BioPredArrayResults
	
	
def readIniFile(iniFile, iniValues):
        data = open(iniFile).read().strip()

        for line in data.split("\n"):
                try:
                        splitTmp = line.strip().split("=")
                        iniValues[splitTmp[0]] = splitTmp[1]
                except Exception,e:
                        pass

        return iniValues

def setInFile(inFile, slimPiniValues):
	slimPiniValues["seqin"]=inFile
	return slimPiniValues

def setOutFile(outfile, slimPiniValues):
	slimPiniValues["seqout"] = outfile
	return slimPiniValues

def setThreshold(threshold, slimPiniValues):
	slimPiniValues["threshold"]= threshold
	return slimPiniValues

slimPiniValues = {}
	
print "Started the slimpred program"
slimPiniValues = readIniFile("/home/testing/public_html/slimsuite/settings/slimpred.ini", slimPiniValues)
#slimPiniValues = readIniFile("~/public_html/Datasets/slimpred/" + value + "/" + value + ".ini")

# change the original ini files by calling the set Methods.
# slimPiniValues = setParam("new value", slimPiniValues)
# Dunno how the new values are passed from formParser?

splitArg = str(sys.argv[1]).strip().split("=")

slimPiniValues = readIniFile(str(splitArg[1]), slimPiniValues)


job_id = os.path.basename(splitArg[1]).split(".")[0]
job_dir = os.path.join(os.path.dirname(splitArg[1]),job_id)
job_root_dir = splitArg[1]

uniprot_acc = open(slimPiniValues['seqin']).read().split("\r")[0].split("|")[1]

#print "In File from server generated ini file: " + slimPiniValues["seqin"]
seqin = slimPiniValues["seqin"]
seqout = slimPiniValues["seqin"]
slimPiniValues = setOutFile(seqout, slimPiniValues)
#print "outfile: " + slimPiniValues["seqout"]
#print "Threshold: " + slimPiniValues["threshold"]

print "Ready to run SLiMPred"
slimPredResults = {}
slimPredResults = SLiMPred(slimPiniValues["seqin"], slimPiniValues["seqout"], slimPiniValues["threshold"] )

print "Launched slimpred - play around with alignments"
curr_file = "/home/compass/public_html/Databases/Alignments/Metazoan/ALN/" + uniprot_acc + ".orthaln.fas"
if(os.path.exists(curr_file)):
	orig_file = "/home/compass/public_html/Databases/Alignments/Metazoan/ALN/" + uniprot_acc + ".orthaln.fas"
	new_file = job_dir + ".orthaln.fas"
	copy_cmd = "cp " + orig_file + " " + new_file
	print copy_cmd
	print os.popen(copy_cmd).read()
	print "copied the file to the working dir"

else:
	print "File doesn't exist - make new alignment"
	gopher_cmd = "python /home/testing/public_html/slimsuite/tools/gopher_V2.py "
	gopher_cmd += " muscle=/home/richard/Bioware/muscle6_bin/muscle6 genspacc=T savespace=F memsaver=F unkspec=F"
	gopher_cmd += " orthdb=/disk3/Databases/ens_loci_proteomes.101018.fas"
	gopher_cmd += "	log=" + job_dir + "gopher.log"
	gopher_cmd += " gopher=" + job_dir + ".seqin"
	print os.popen(gopher_cmd).read()
	print "Made new alignment?"
	#copy the newly made gopher file down a dir to where the drawAlignment program is waiting for it.
	origALNFile = "/home/testing/public_html/Datasets/slimpred/" + job_id + "/ALN/" + uniprot_acc + ".orthaln.fas"
	if(os.path.exists(origALNFile)):
		origALNFile = origALNFile
	else:
		origALNFile = job_dir + ".seqin"
	newALNFile = job_dir + ".orthaln.fas"
	copyALN_cmd = "cp " + origALNFile + " " + newALNFile
	print copyALN_cmd
	print os.popen(copyALN_cmd).read()
	print "Sorry"	

# clustalw=/home/people/nhaslam/clustalw1.82/clustalw blastpath=/opt/blast/bin/ muscle=/home/people/nhaslam/muscle/muscle3.8.31/src/muscle gopher=wormpep.WS217gopher.fa i=1 orthdb=ens_loci_proteomes.101018.fas gnspacc=T
#mkALNdir_cmd = "mkdir /home/testing/public_html/Datasets/slimpred/" + job_id + "/AlignmentPNG/"
#print os.popen(mkALNdir_cmd).read()

#plot_distribution_cmd = "python /home/dev/public_html/cgi-bin/Utilities/ned_plotDistribution.py "
plot_distribution_cmd = "python /home/testing/public_html/slimsuite/libraries/ned_plotDistribution3.py "
plot_distribution_cmd += "-a " + job_dir + ".orthaln.fas "
#plot_distribution_cmd += "-a /home/compass/public_html/Databases/Alignments/Metazoan/ALN/" + uniprot_acc + ".orthaln.fas "
plot_distribution_cmd += "-g plots,alignment,slims -P 100 "
plot_distribution_cmd += "-u /home/compass/public_html/Databases/Uniprot/ "
plot_distribution_cmd += "-U /home/compass/public_html/cgi-bin/Bioware/iupred/iupred "
plot_distribution_cmd += "-GSLiMPred:" + job_dir + ".seqin.SLiMpred:green "
plot_distribution_cmd += "-D" + job_dir + ".pdf -HT -r 1"
curPdfLoc = job_dir + ".pdf"
newPdfLoc = "/home/testing/public_html/Datasets/slimpred/" + job_id + "/" + uniprot_acc + ".pdf"
print "Got here made the plots? + " + job_dir + " curPdfLoc: " + curPdfLoc + " Uniprot acc points to: " + uniprot_acc + "New Loc: " + newPdfLoc

print plot_distribution_cmd
print os.popen(plot_distribution_cmd).read()
os.rename(curPdfLoc,newPdfLoc)
