public int read(int numBits) throws IOException {
        int res = 0;
        while (numBits > 0 && !eof) {
            if (remaining == 0) {
                tmp = input.read();
                if (tmp == -1) {
                    eof = true;
                    return -1;
                }
                remaining = 8;
            }
            int toNibble = Math.min(remaining, numBits);
            int toLeave = (remaining-toNibble);
            int leaveMask = (1<<toLeave)-1;

            res = res << toNibble;
            res += (tmp>>toLeave);
            tmp = tmp & leaveMask;

            remaining -= toNibble;
            numBits -= toNibble;
        }
        if (eof) return -1;
        return res;
    }