private int decodeLength() throws Asn1Exception {
        int length = 0;

        //
        // There must be at least one byte available
        //
        if (residualLength < 1)
            throw new Asn1Exception("Attempt to read past end of stream");

        //
        // The high-order bit is set in the first byte of the L field
        // if the length is encoded in multiple bytes
        //
        if (stream[next] >= 0) {
            length = (int)stream[next++];
            residualLength--;
        } else {
            int count = (int)stream[next]&0x7f;

            if (count > 4)
                throw new Asn1Exception("Length field at offset "+next+" is too long");

            next++;
            residualLength--;

            if (residualLength < count)
                throw new Asn1Exception("Attempt to read past end of stream");

            for (int i=0; i<count; i++)
                length = (length<<8)|((int)stream[next++]&0xff);

            residualLength -= count;
        }

        return length;
    }