/* bit_res.h

      Declarations for Bit Reservoir for Layer III

   Adapted from the public c code by Jeff Tsay. */

//
//
// optimizing hgetbits() to getonebit() by Timo Jantunen (jeti@iki.fi)
// Also changed buf and bufmask from 32 bits to 8 bit.
//


#ifndef BIT_RES_H
#define BIT_RES_H

#include "all.h"

#define BUFSIZE 4096

typedef unsigned char uint8;

class Bit_Reserve {

private:

  uint32 offset, totbit, buf_byte_idx;
  uint8 *buf;
  uint32 buf_bit_idx;
  uint8 *putmask;

public:

  Bit_Reserve();
  ~Bit_Reserve();

  uint32 hsstell() { return(totbit); }
  uint32 hgetbits(uint32 N);

  void rewindNbits(int32 N);
  void rewindNbytes(int32 N);

  inline uint32 Bit_Reserve::hgetonebit() {
    // read one bit from the bit stream
    totbit ++;

    if (buf_bit_idx == 0) {
      buf_bit_idx = 8;buf_byte_idx++;
    }
    return (buf[buf_byte_idx & 0xfff] >> --buf_bit_idx)&1;
  }

  inline void Bit_Reserve::hputbuf(uint8 val) {
    // write 8 bits into the bit stream
    buf[offset & 0xfff] = val;
    offset++;
  }

};

#endif
