<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
 def longestorf(args):
 """ %prog longestorf fastafile Find longest ORF for each sequence in fastafile. """

    p = OptionParser(longestorf.__doc__)
    p.add_option("--ids", action="store_true",
                 help="Generate table with ORF info [default: %default]")
    opts, args = p.parse_args(args)

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

    fastafile, = args
    pf = fastafile.rsplit(".", 1)[0]
    orffile = pf + ".orf.fasta"
    idsfile = None
    if opts.ids:
        idsfile = pf + ".orf.ids"
        fwids = open(idsfile, "w")

    f = Fasta(fastafile, lazy=True)
    fw = must_open(orffile, "w")
    before, after = 0, 0
    for name, rec in f.iteritems_ordered():
        cds = rec.seq
        before += len(cds)
        # Try all six frames
        orf = ORFFinder(cds)
        lorf = orf.get_longest_orf()
        newcds = Seq(lorf)
        after += len(newcds)
        newrec = SeqRecord(newcds, id=name, description=rec.description)
        SeqIO.write([newrec], fw, "fasta")
        if idsfile:
            print("\t".join((name, orf.info)), file=fwids)

    fw.close()
    if idsfile:
        fwids.close()

    logging.debug("Longest ORFs written to `{0}` ({1}).".\
                    format(orffile, percentage(after, before)))

    return orffile