public int readBits(int SampleBits) throws IOException
    {
        while (bitsInCache < SampleBits)
        {
            int next = is.read();

            if (next < 0)
            {
                if (tiffLZWMode)
                {
                    // pernicious special case!
                    return 257;
                }
                return -1;
            }

            int newByte = (0xff & next);

            if (byteOrder == BYTE_ORDER_NETWORK) // MSB, so add to right
                bitCache = (bitCache << 8) | newByte;
            else if (byteOrder == BYTE_ORDER_INTEL) // LSB, so add to left
                bitCache = (newByte << bitsInCache) | bitCache;
            else
                throw new IOException("Unknown byte order: " + byteOrder);

            bytesRead++;
            bitsInCache += 8;
        }
        int sampleMask = (1 << SampleBits) - 1;

        int sample;

        if (byteOrder == BYTE_ORDER_NETWORK) // MSB, so read from left
        {
            sample = sampleMask & (bitCache >> (bitsInCache - SampleBits));
        }
        else if (byteOrder == BYTE_ORDER_INTEL) // LSB, so read from right
        {
            sample = sampleMask & bitCache;
            bitCache >>= SampleBits;
        }
        else
            throw new IOException("Unknown byte order: " + byteOrder);

        int result = sample;

        bitsInCache -= SampleBits;
        int remainderMask = (1 << bitsInCache) - 1;
        bitCache &= remainderMask;

        return result;
    }