u32 wbuf; // pending output in low bits

unsigned obj; // input bits, LSB first

unsigned n=0; // number of bits in bits (0..32)

u32 mask[29]={1,3,7,15,31,63,127,255,511,1023,2047,4095,8191,1 6383,32767,65535,131071,262143,524287,1048575,2097 151,4194303,8388607,16777215,33554431,67108863,134 217727,268435455,536870911};

void Wbits(unsigned x, int bit)

{ // write k (0..25) bits of x

x&=mask[bit-1];

wbuf|=x<<n;

n+=bit;

while (n>7) AUXBuffer[ascritto++]=wbuf, wbuf>>=8, n-=8;

}

int Rbits(int bit)

{ // write k (0..25) bits of x

while (n<bit)

{

wbuf+=AUXBuffer[ascritto++]<<n;

n+=8;

}

obj=wbuf&mask[bit-1];

wbuf>>=bit;

n-=bit;

return obj;

}

void encode(bool x)

{ // write k (0..25) bits of x

wbuf|=x<<n;

n++;

if (n>7) AUXBuffer[ascritto++]=wbuf, wbuf>>=8, n-=8;

}

int decode()

{ // write k (0..25) bits of x

(!n)?(wbuf+=AUXBuffer[ascritto++]<<n, n + = 8 ) : (0);

obj=wbuf&1;

wbuf>>=1;

n--;

return obj;

}

void flush()

{ // write last byte

if (n>0) AUXBuffer[ascritto++]=wbuf, wbuf=0, n=0;

}