#!/usr/bin/env python

import optparse
import sys

import argweaver
from argweaver import argweaverc

from compbio import arglib


o = optparse.OptionParser(
    usage="%prog ARG_FILE SMC_FILE",
    description="""
Converts an ARG stored in *.arg format to *.smc format.
If `--ntimes` and `--maxtime` are given, the ARG is also discretized.
""")
o.add_option("-t", "--ntimes", type="int",
             help="If given, ARG will be discretized in 'ntimes' time points")
o.add_option("", "--maxtime", type="float",
             help="Maximum time discretized time point")

conf, args = o.parse_args()


# Parse arguments
if len(args) != 2:
    o.print_help()
    sys.exit(1)

arg_file = args[0]
smc_file = args[1]

arg = arglib.read_arg(arg_file)

if conf.ntimes:
    # discretize ARG according to given times
    if not conf.maxtime:
        print >>sys.stderr, 'option --maxtime is needed'
        sys.exit(1)

    times = argweaver.get_time_points(ntimes=conf.ntimes, maxtime=conf.maxtime)
    argweaver.discretize_arg(arg, times)
    arg = arglib.smcify_arg(arg)

    # use C-interface for speed
    trees, names = argweaverc.arg2ctrees(arg, times)
    argweaverc.write_local_trees(smc_file, trees, names, times, len(times))

else:
    # convert ARG without discretization
    arg = arglib.smcify_arg(arg)
    smc = argweaver.arg2smc(arg)
    argweaver.write_smc(smc_file, smc)
