private int nextCode() {
        int fillbits = bitspercode;
        int value = 0;
        if (bytepos >= buf.limit() - 1) {
            return -1;
        }
        while (fillbits > 0) {
            int nextbits = buf.get(bytepos);  // bitsource
            int bitsfromhere = 8 - bitpos;  // how many bits can we take?
            if (bitsfromhere > fillbits) { // don't take more than we need
                bitsfromhere = fillbits;
            }
            value |= ((nextbits >> (8 - bitpos - bitsfromhere)) &
                    (0xff >> (8 - bitsfromhere))) << (fillbits - bitsfromhere);
            fillbits -= bitsfromhere;
            bitpos += bitsfromhere;
            if (bitpos >= 8) {
                bitpos = 0;
                bytepos++;
            }
        }
        return value;
    }