def _readVariableLengthInt(data, startOffset, limit=4):
    """
    Read a variable-length integer (as SSEQ encodes them) from `data`
    beginning at `startOffset`, limiting the number of read bytes to
    `limit`.
    
    While the code below looks complicated, the method to read such an
    integer is simple:
    - Read a byte. AND it with 0x7F for the part relevant to the
      integer value.
    - If its MSB (that you just trimmed off) is set, left-shift the int
      value by 7, move on to the next byte and repeat.

    So you read 7 bits as a time for as long as the MSB continues to be
    set.
    """
    offset = startOffset
    value = data[offset] & 127
    offset += 1
    length = 0
    while data[offset - 1] & 128:
        value <<= 7
        value |= data[offset] & 127
        offset += 1
        length += 1
        if length > limit:
            raise ValueError('Read variable-length int past its end')
    return value
