#include <math.h>
#include <stdlib.h>
#include "CoefficientStream.h"
#include "Common.h"


// Try to be as much platform independent as possible...
#define BITBITMAP     (8*sizeof(unsigned int))
#define MOSTSIGBITMAP 0x80000000


CoefficientStore::CoefficientStore(const int nt,const int nc)
{
  int numbmp;

  numbmp = nt/BITBITMAP;
  numbmp++;
  bitmap = new unsigned int[numbmp];
  if (nc!=0)
    coefs = new COLOR[nc];
  else 
    coefs = NULL;
  nnc = sizeof(unsigned int)*numbmp + nc*sizeof(float)*3;
}


CoefficientStore::~CoefficientStore()
{
  if (bitmap!=NULL)
    delete bitmap;

  if (coefs!=NULL)
    delete coefs;
}

int CoefficientStore::getNumBytes()
{
  return nnc;
}


CoefficientStream::CoefficientStream()
{
  cs = NULL;
}


void CoefficientStream::setCoefficientStore(CoefficientStore *ncs)
{
  cs = ncs;
}


void CoefficientStream::startRead()
{
  curbitmap = cs->bitmap;
  curcoef = cs->coefs;
  val = 0;
  delta = BITBITMAP-1;
}


COLOR* CoefficientStream::nextRead()
{
  COLOR *c;

  delta = (delta+1) % BITBITMAP;
  if (delta == 0)
    {
      val = *curbitmap;
      curbitmap++;
    }
  else
    val <<= 1;

  if (val & MOSTSIGBITMAP)
    {
      c = curcoef;
      curcoef++;
    }
  else
    {
      c = &zerorad;
    }

  return c;
}


void CoefficientStream::startWrite()
{
  curbitmap = cs->bitmap;
  curcoef = cs->coefs;
  val = 0;
  delta = 0;
}


void CoefficientStream::skipWrite()
{
  val <<= 1;
  delta = (delta+1) % BITBITMAP;
  if (delta == 0)
    {
      *curbitmap = val;
      curbitmap++;
      val = 0;
    }
}


void CoefficientStream::nextWrite(COLOR *c)
{
  //COLORCOPY(*c,*curcoef);

  *curcoef = *c;
  curcoef++;
  val <<= 1;
  val |= 1;
  delta = (delta+1) % BITBITMAP;
  if (delta == 0)
    {
      *curbitmap = val;
      curbitmap++;
      val = 0;
    }
}


void CoefficientStream::endWrite()
{
  if (delta!=0)
    *curbitmap = (val<<(BITBITMAP-delta));
}





