#!/usr/bin/env python
# run bionj with standard command-line interface

import sys, os, shutil
import optparse

from rasmus import util, treelib
from compbio import phylip, fasta, phylo
from compbio import phylorun as phy


def write_dist_matrix(mat, labels, out=sys.stdout):
    out = util.open_stream(out, "w")
    
    out.write("%d\n" % len(mat))
    
    for i in range(len(mat)):
        out.write("%s  " % labels[i])        
        for val in mat[i]:
            out.write("%10f " % val)
        out.write("\n")



o = optparse.OptionParser()
phy.add_common_options(o)
conf, files = phy.parse_common_options(o)

result = 0
for fn in files:
    basename = phy.get_basename(fn, conf)
    
    outdir = basename + conf.outputext
    phy.make_output_dir(outdir)
    align = fasta.read_fasta(basename + conf.alignext)    

    if len(align) <= 2:
        continue

    
    # make temp files
    distfile = outdir + "/dist"
    treefile = basename + conf.treeext
    
    # find distances    
    if conf.seqtype == "pep":
        labels = phylip.protdist(align, distfile, verbose=True)
    else:
        labels = phylip.dnadist(align, distfile, verbose=True)

    labels_junk, distmat = phylip.read_dist_matrix(distfile)
    write_dist_matrix(distmat, labels, distfile)

    if not conf.opttree:
        print "using usertree"
        
        usertree = treelib.read_tree(basename + conf.usertreeext)    
        tree = phylo.neighborjoin(distmat, labels, usertree=usertree)
        tree.write(treefile)

    else:

        util.tic()
        cmd = "echo -n '%s\n%s' | bionj > '%s/out'" %\
              (distfile, treefile, outdir)
        print cmd

        out = open(outdir + "/cmd", "w")
        out.write(cmd)
        out.close()
        if os.system(cmd) != 0:
            open(outdir + "/error", "w").close()
            result = 1
        out = open("%s/time" % outdir, "w")
        out.write(str(util.toc()) + "\n")
        out.close()
        


sys.exit(result)
