def main( argv = None ):
    """script main.

    parses command line options in sys.argv, unless *argv* is given.
    """

    if DISABLE:
        print "# tophat_segment_juncs.py disabled"
        argv[0] = "segment_juncs.original"
        runCommand( argv , "segment_juncs.log" )
        return 0

    E.Start( no_parsing = True )

    # collect arguments
    parser = argparse.ArgumentParser(description='Process tophat options.')
    parser.add_argument('-p', '--num-threads', metavar='N', type=int, dest='nthreads',
                         help='number of threads')
    parser.add_argument('--version', action='version', version='%(prog)s')
    options, args = parser.parse_known_args( argv[1:] )

    E.info( "parallelizing segment juncs with %i threads" % options.nthreads )
    
    x = argv.index("--ium-reads") + 1
    
    all_options = argv[1:x]

    (input_missing_reads, input_genome, 
     output_junctions, 
     output_insertions, output_deletions,
     input_left_all_reads,
     input_left_all_map,
     input_left_segments_maps ) = argv[x:x + 8]

    input_left_segments_maps = input_left_segments_maps.split(",")

    if len(argv) > x + 8:
        ( input_right_all_reads,
          input_right_all_map,
          input_right_segments_maps ) = argv[x+8:x+11]
        input_right_segments_maps = input_right_segments_maps.split(",")
    else:
        input_right_all_reads = ""
        input_right_all_map = ""
        input_right_segments_maps = []

    keys = set()
    
    # some filenames might appear multiple times
    files_to_split = set([input_left_all_map, \
                              input_right_all_map ] +\
                             input_left_segments_maps +\
                             input_right_segments_maps )

    E.info( "splitting %i files" % len(files_to_split))

    ## split all map files by chromosome
    for filename in files_to_split:
        if filename == "": continue
        E.info("splitting %s" % filename )
        base, ext = os.path.splitext( filename )

        f = glob.glob( "%s.input.*%s" % (filename, ext) )
        if f:
            E.info("files already exist - skipping" )
            keys.update( [ re.match("%s.input.(\S+)%s" % (filename,ext), x ).groups()[0] for x in f ] )
            continue
        
        infile = IOTools.openFile( filename )

        outfiles = IOTools.FilePool( filename + ".input.%s" + ext )

        for line in infile:
            key = line.split("\t")[2]
            keys.add( key )
            outfiles.write( key, line )

        outfiles.close()

    # keys = set( ["chr1", "chr2", "chr3", "chr4", "chr5",
    #              "chr6", "chr7", "chr8", "chr9", "chr10",
    #              "chr11", "chr12", "chr13", "chr14", "chr15",
    #              "chr16", "chr17", "chr18", "chr19", "chr20",
    #              "chr21", "chr22", "chrX", "chrY", "chrM" ] )

    E.info( "working on %i contigs: %s" % (len(keys), list(keys)))

    pool = multiprocessing.pool.ThreadPool( options.nthreads )
    #pool = threadpool.ThreadPool( THREADS )

    tmpdir = os.path.dirname( input_left_all_reads )
    logdir = os.path.join( tmpdir[:-len("tmp")], "logs" )

    if not os.path.exists(logdir):
        raise IOError( "can not find logdir %s" % logdir )

    args = []
    for key in keys:

        def modout( old, key ):
            if not old:return ""
            _, ext = os.path.splitext( old )
            return old + ".output.%s%s" % (key, ext)

        def modin( old, key ):
            if not old:return ""
            _, ext = os.path.splitext( old )
            return old + ".input.%s%s" % (key,ext)

        def modgenome( old, key ):
            dirname, filename = os.path.split(old)
            genome, ext = os.path.splitext( filename )
            if genome.lower().endswith("_cs"): genome = genome[:-3]
            new = os.path.join( dirname, genome + ".perchrom", key + ext )
            if not os.path.exists(new):
                raise ValueError( "can not find chromoseme file %s" % new )
            return new

        cmd = ["segment_juncs"] +\
            all_options +\
            [input_missing_reads,  \
                 modgenome(input_genome,key), \
                 modout(output_junctions,key),\
                 modout(output_insertions,key),\
                 modout(output_deletions,key),\
                 input_left_all_reads,\
                 modin( input_left_all_map, key ),\
                 ",".join( [ modin( x, key ) for x in input_left_segments_maps ] ),\
                 input_right_all_reads,\
                 modin( input_right_all_map, key ),\
                 ",".join( [ modin( x, key ) for x in input_right_segments_maps ] ) ]


        logfile = os.path.join(logdir, "segment_juncs_%s.log" % key )
        args.append( (cmd,logfile) )

    E.info( "submitting %i jobs" % len(keys) )

    pool.map( runCommand, args, chunksize = 1 )
    pool.close()
    pool.join()

    E.info("all jobs finished successfully" )

    E.info("merging results")
    ## merge results
    for filename in (output_junctions, output_insertions, output_deletions):
        outfile = open(filename, "w")
        for inf in glob.glob( filename + ".output.*" ):
            infile = open( inf, "r" )
            outfile.write( infile.read() )
            infile.close()
        outfile.close()
        
    E.info("results merged")

    ## cleaning up is done automatically by tophat
    E.info("cleaning up" )
    for f in glob.glob( os.path.join( tmpdir, "*.output.*") ) +\
            glob.glob( os.path.join( tmpdir, "*.input.*") ):
        os.remove(f)

    ## write footer and output benchmark information.
    E.Stop()
dataset/ETHPy150Open CGATOxford/cgat/obsolete/tophat_segment_juncs.py/main/original