'Parse an MH sequence specification into a message list.
Attempt to mimic mh-sequence(5) as close as possible.
Also attempt to mimic observed behavior regarding which
conditions cause which error messages.'

def parsesequence(self, seq):

    all = self.listmessages()
    if (not all):
        raise Error, ('no    messages    in    %s' % self.name)
    if (seq == 'all'):
        return all
    i = seq.find(':')
    if (i >= 0):
        (head, dir, tail) = (seq[:i], '', seq[(i + 1):])
        if (tail[:1] in '-+'):
            (dir, tail) = (tail[:1], tail[1:])
        if (not isnumeric(tail)):
            raise Error, ('bad    message    list    %s' % seq)
        try:
            count = int(tail)
        except (ValueError, OverflowError):
            count = len(all)
        try:
            anchor = self._parseindex(head, all)
        except Error as msg:
            seqs = self.getsequences()
            if (head not in seqs):
                if (not msg):
                    msg = ('bad    message    list    %s' % seq)
                raise Error, msg, sys.exc_info()[2]
            msgs = seqs[head]
            if (not msgs):
                raise Error, ('sequence    %s    empty' % head)
            if (dir == '-'):
                return msgs[(- count):]
            else:
                return msgs[:count]
        else:
            if (not dir):
                if (head in ('prev', 'last')):
                    dir = '-'
            if (dir == '-'):
                i = bisect(all, anchor)
                return all[max(0, (i - count)):i]
            i = bisect(all, (anchor - 1))
            return all[i:(i + count)]
    i = seq.find('-')
    if (i >= 0):
        begin = self._parseindex(seq[:i], all)
        end = self._parseindex(seq[(i + 1):], all)
        i = bisect(all, (begin - 1))
        j = bisect(all, end)
        r = all[i:j]
        if (not r):
            raise Error, ('bad    message    list    %s' % seq)
        return r
    try:
        n = self._parseindex(seq, all)
    except Error as msg:
        seqs = self.getsequences()
        if (seq not in seqs):
            if (not msg):
                msg = ('bad    message    list    %s' % seq)
            raise Error, msg
        return seqs[seq]
    if (n not in all):
        if isnumeric(seq):
            raise Error, ("message    %d    doesn't    exist" % n)
        else:
            raise Error, ('no    %s    message' % seq)
    else:
        return [n]
