#!/usr/bin/env python
# Programmer : zhuxp
# Date: 
# Last-modified: 02-20-2014, 16:01:22 EST
from bam2x import __version__ as VERSION
import os,sys,argparse
import signal
signal.signal(signal.SIGPIPE,signal.SIG_DFL)
from bam2x.Run import commands
from bam2x.MRun import commands as mcmd
import imp

def ParseArg():
    ''' This Function Parse the Argument '''
    p=argparse.ArgumentParser( description = 'bam2x', epilog='')
    p.add_argument('-v','--version',action='version',version='%(prog)s '+VERSION)
    
    
    group=argparse.ArgumentParser(add_help=False)
    group.add_argument('-i','--input',dest='input',default='stdin',type=str,help="input file Default: %(default)s")
    group.add_argument('-o','--output',dest='output',default='stdout',type=str,help="output file Default: %(default)s")
    
    mcpu_group=argparse.ArgumentParser(add_help=False)
    mcpu_group.add_argument('-n','--num_cpus',dest="num_cpus",type=int,default=4,help="number of cpus DEFAULT: %(default)i")
    
    subs=p.add_subparsers(help="subcommand help",dest="sub")
    for i in commands.keys():
        pi=subs.add_parser(i,help=commands[i].help(),parents=[group])
        commands[i].set_parser(pi)
    for i in mcmd.keys():
        pi=subs.add_parser(i,help=mcmd[i].help(),parents=[group,mcpu_group])
        mcmd[i].set_parser(pi)
    if matplotlib_found:
        from bam2x.Run.Plot import commands as plot_commands
        for i in plot_commands.keys():
            pi=subs.add_parser(i,help=plot_commands[i].help(),parents=[group])
            plot_commands[i].set_parser(pi)
    if len(sys.argv)==1:
        print >>sys.stderr,p.print_help()
        exit(0)
    if len(sys.argv)==2:
        print >>sys.stderr,p.parse_args([sys.argv[1],'--help'])
        exit(0)
    return p.parse_args()
def Main():
    args=ParseArg()
    if commands.has_key(args.sub):
        commands[args.sub].run(args)
    elif mcmd.has_key(args.sub):
        mcmd[args.sub].run(args)

    
if __name__=="__main__":
    global matplotlib_found
    try: 
        matplotlib_info=imp.find_module('matplotlib')
        matplotlib_found=True
    except ImportError:
        matplotlib_found=False
    Main()








