#include <stdlib.h>
#include <stdio.h>

#include "bitio_m_abstract.h"
#include "bitio_m_mems.h"

/**
 * Create decoding "stream"/"file"
 */
mems_bitio_buffer::mems_bitio_buffer()
{
}

mems_bitio_buffer::mems_bitio_buffer(unsigned char *readbuffer, mg_s_long _pos)
{ 
  base = readbuffer;
  pos  = _pos;
}

void mems_bitio_buffer::encodeStart()
{
  // Do nothing
}


void mems_bitio_buffer::error()
{
  fprintf(stderr, "Unexpected EOF in \"%s\" on line %d\n", __FILE__, __LINE__);
  exit(1);
}


void mems_bitio_buffer::seek(mg_u_long toPos)
{ 
  pos = toPos;
}

mg_u_long mems_bitio_buffer::position()
{
  return pos;
}

mg_s_long mems_bitio_buffer::addff(mg_s_long b)
{
  do
    {
      b = b + b + (base[pos>>3] & (0x80 >> (pos & 0x07)) != 0);
      ++pos;
    }
  while(0);

  return b;
}

mg_s_long mems_bitio_buffer::add00(mg_s_long b)
{
  return addff(b);
}

int mems_bitio_buffer::bit()
{
  ++pos;
  return ((base[(pos-1)>>3] & (0x80 >> ((pos-1) & 0x07))) != 0);
}

void mems_bitio_buffer::encodeBit(int bit)
{
  if (bit)
    base[pos>>3] |= 0x80 >> (pos & 0x07);
  else
    base[pos>>3] &= 0xff7f >> (pos & 0x07);
  ++pos;
}

void mems_bitio_buffer::flush()
{
  // do nothing
}

void mems_bitio_buffer::done()
{
  // do nothing
}

void mems_bitio_buffer::encodeDone()
{
  flush();
}

