def sort(args):
    p = OptionParser(sort.__doc__)
    p.add_option("-i", "--inplace", dest="inplace",
            default=False, action="store_true",
            help="Sort bed file in place [default: %default]")
    p.add_option("-u", dest="unique",
            default=False, action="store_true",
            help="Uniqify the bed file")
    p.add_option("--accn", default=False, action="store_true",
            help="Sort based on the accessions [default: %default]")
    p.set_outfile(outfile=None)
    p.set_tmpdir()
    opts, args = p.parse_args(args)
    if len(args) != 1:
        sys.exit(not p.print_help())
    bedfile, = args
    inplace = opts.inplace
    if not inplace and ".sorted." in bedfile:
        return bedfile
    sortedbed = opts.outfile
    if inplace:
        sortedbed = bedfile
    elif opts.outfile is None:
        pf, sf = op.basename(bedfile).rsplit(".", 1)
        sortedbed = pf + ".sorted." + sf
    sortopt = "-k1,1 -k2,2n -k3,3n -k4,4" if not opts.accn else \
              "-k4,4 -k1,1 -k2,2n -k3,3n"
    cmd = "sort"
    if opts.tmpdir:
        cmd += " -T {0}".format(opts.tmpdir)
    if opts.unique:
        cmd += " -u"
    cmd += " {0} {1} -o {2}".format(sortopt, bedfile, sortedbed)
    if inplace or need_update(bedfile, sortedbed):
        sh(cmd)
    return sortedbed