#!python

import os

from gotran.model.loadmodel import load_ode
from gotran.codegeneration.codegenerators import CCodeGenerator
from gotran.common.options import parameters
from gotran.common import error, list_timings, Timer, info

def main(filename, params):
    """
    Create a c header file from a gotran model
    """
    timer = Timer("Generate C code from {}".format(filename))

    # Load Gotran model
    ode = load_ode(filename)

    # Create a C code generator
    gen = CCodeGenerator(params)

    output = params.output

    if output:
        if not(len(output)>2 and output[-2:] == ".h"):
            output += ".h"
    else:
        output = filename.replace(".ode", "")+".h"

    info("")
    info("Generating C code for the {0} ode...".format(ode.name))
    code = gen.module_code(ode)
    info("  done.")
    with open(output, "w") as f:
        if params.system_headers:
            f.write("#include <math.h>\n")
            f.write("#include <string.h>\n")

        f.write(code)

    del timer
    
    if params.list_timings:
        list_timings()

if __name__ == "__main__":
    import sys, os
    from modelparameters.parameterdict import *

    generation_params=CCodeGenerator.default_parameters()
    
    params = ParameterDict(\
        list_timings = Param(False, description="If true timings for reading "\
                             "and evaluating the model is listed."),
        system_headers = Param(True, description="If true system "\
                               "headers needed to compile moudle is "\
                               "included."),\
        output = Param("", description="Specify output file name"),\
        **dict((name, param) for name, param in list(generation_params.items()) \
        if name not in ["class_code"]))
    params.parse_args(usage="usage: %prog FILE [options]")#sys.argv[2:])
    
    if len(sys.argv) < 2:
        raise RuntimeError("Expected a single gotran file argument")

    if not os.path.isfile(sys.argv[1]):
        raise IOError("Expected the argument to be a file")
	 
    file_name = sys.argv[1]
    main(file_name, params)
