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

import sys, os, shutil
import optparse

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


o = optparse.OptionParser()
phy.add_common_options(o)
o.add_option("-n", "--ngen", dest="ngen", default=10000,
             type="int")
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

    if conf.usertreeext:
        usertree = treelib.read_tree(basename + conf.usertreeext)
        treelib.unroot(usertree, newCopy=False)
    else:
        usertree = None

    nexfilename = outdir + "/infile.nex"    
    options = {"ngen": conf.ngen}
    mrbayes.setDefaultOptions(options)
    
    options["burninfrac"] = .25
    options["relburnin"] = "yes"
    
    # force best binary tree (if possible)
    options["extra"] += "sumt contype=allcompat;"
        
    # write input file
    out = file(nexfilename, "w")
    mrbayes.writeNexus(out, align.keys(), align.values(), conf.seqtype, options)
    mrbayes.writeMrbayesOptions(out, options, seqtype=conf.seqtype)
    out.close()
    

    cmd = "mb '%s' > '%s/out'" % (nexfilename, 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
    else:
        tree = mrbayes.readNexusConTree(file(nexfilename + ".con"))
        tree.write(basename + conf.treeext)


sys.exit(result)
