public final int readBits(int count) throws IOException
    {

        if (count <= 32) // catch-all
        {
            int result = 0;
            //            int done = 0;

            if (cacheBitsRemaining > 0)
            {
                if (count >= cacheBitsRemaining)
                {
                    result = ((1 << cacheBitsRemaining) - 1) & cache;
                    count -= cacheBitsRemaining;
                    cacheBitsRemaining = 0;
                }
                else
                {
                    //                    cache >>= count;
                    cacheBitsRemaining -= count;
                    result = ((1 << count) - 1) & (cache >> cacheBitsRemaining);
                    count = 0;
                }
            }
            while (count >= 8)
            {
                cache = is.read();
                if (cache < 0)
                    throw new IOException("couldn't read bits");
                System.out.println("cache 1: " + cache + " ("
                        + Integer.toHexString(cache) + ", "
                        + Integer.toBinaryString(cache) + ")");
                bytesRead++;
                result = (result << 8) | (0xff & cache);
                count -= 8;
            }
            if (count > 0)
            {
                cache = is.read();
                if (cache < 0)
                    throw new IOException("couldn't read bits");
                System.out.println("cache 2: " + cache + " ("
                        + Integer.toHexString(cache) + ", "
                        + Integer.toBinaryString(cache) + ")");
                bytesRead++;
                cacheBitsRemaining = 8 - count;
                result = (result << count)
                        | (((1 << count) - 1) & (cache >> cacheBitsRemaining));
                count = 0;
            }

            return result;
        }

        throw new IOException("BitInputStream: unknown error");

    }