def sort(args):
    """
    %prog sort gffile

    Sort gff file using plain old unix sort based on [chromosome, start coordinate].
    or topologically based on hierarchy of features using the gt (genometools) toolkit
    """
    valid_sort_methods = ("unix", "topo")

    p = OptionParser(sort.__doc__)
    p.add_option("--method", default="unix", choices=valid_sort_methods,
                 help="Specify sort method [default: %default]")
    p.add_option("-i", dest="inplace", default=False, action="store_true",
                 help="If doing a unix sort, perform sort inplace [default: %default]")
    p.set_tmpdir()
    p.set_outfile()
    p.set_home("gt")
    opts, args = p.parse_args(args)

    if len(args) != 1:
        sys.exit(not p.print_help())

    gffile, = args
    sortedgff = opts.outfile
    if opts.inplace:
        if opts.method == "topo" or (opts.method == "unix" and gffile in ("-", "stdin")):
            logging.error("Cannot perform inplace sort when method is `topo`" + \
                " or method is `unix` and input is `stdin` stream")
            sys.exit()

    if opts.method == "unix":
        cmd = "sort"
        cmd += " -k1,1 -k4,4n {0}".format(gffile)
        if opts.tmpdir:
            cmd += " -T {0}".format(opts.tmpdir)
        if opts.inplace:
            cmd += " -o {0}".gffile
            sortedgff = None
        sh(cmd, outfile=sortedgff)
    elif opts.method == "topo":
        GT_HOME = opts.gt_home
        if not op.isdir(GT_HOME):
            logging.error("GT_HOME={0} directory does not exist".format(GT_HOME))
            sys.exit()
        cmd = "{0}".format(op.join(GT_HOME, "bin", "gt"))
        cmd += " gff3 -sort -tidy -retainids -addids no {0}".format(gffile)
        sh(cmd, outfile=sortedgff)
%prog sort gffile

    Sort gff file using plain old unix sort based on [chromosome, start coordinate].
    or topologically based on hierarchy of features using the gt (genometools) toolkit