static size_t i2c_ibuf(const unsigned char *b, size_t blen, int neg,
                       unsigned char **pp)
{
    int pad = 0;
    size_t ret, i;
    unsigned char *p, pb = 0;
    const unsigned char *n;

    if (b == NULL || blen == 0)
        ret = 1;
    else {
        ret = blen;
        i = b[0];
        if (ret == 1 && i == 0)
            neg = 0;
        if (!neg && (i > 127)) {
            pad = 1;
            pb = 0;
        } else if (neg) {
            if (i > 128) {
                pad = 1;
                pb = 0xFF;
            } else if (i == 128) {
                /*
                 * Special case: if any other bytes non zero we pad:
                 * otherwise we don't.
                 */
                for (i = 1; i < blen; i++)
                    if (b[i]) {
                        pad = 1;
                        pb = 0xFF;
                        break;
                    }
            }
        }
        ret += pad;
    }
    if (pp == NULL)
        return ret;
    p = *pp;

    if (pad)
        *(p++) = pb;
    if (b == NULL || blen == 0)
        *p = 0;
    else if (!neg)
        memcpy(p, b, blen);
    else {
        /* Begin at the end of the encoding */
        n = b + blen - 1;
        p += blen - 1;
        i = blen;
        /* Copy zeros to destination as long as source is zero */
        while (!*n && i > 1) {
            *(p--) = 0;
            n--;
            i--;
        }
        /* Complement and increment next octet */
        *(p--) = ((*(n--)) ^ 0xff) + 1;
        i--;
        /* Complement any octets left */
        for (; i > 0; i--)
            *(p--) = *(n--) ^ 0xff;
    }

    *pp += ret;
    return ret;
}