#include "ibitstream.h"

CIBitStream::CIBitStream(void){
	m_fhd = 0;
	m_iFilled = 0;
	m_lData = 0;

	int i;
	long l =0;
	for(i=0; i<32; i++){
		m_plMask[i] = l;
		l<<=1;
		l|=1;
	}
}

CIBitStream::~CIBitStream(void){
	if(m_fhd){
		fclose(m_fhd);
	}
}

void CIBitStream::fopen(const char *sz1, const char *sz2){
	m_fhd = ::fopen(sz1,sz2);
}

long CIBitStream::read(int bits){
	long lTemp;

	if(m_iFilled ==0){
		fread(&m_lData,sizeof(long),1,m_fhd);
		m_iFilled = 32;
	}

	if(m_iFilled - bits >= 0){
		lTemp = m_lData;
		lTemp >>= (m_iFilled - bits);
		lTemp &= ((1<<bits)-1);
		m_iFilled -= bits;
		return lTemp;
	}
	else{
		int iLeft = bits - m_iFilled;
		lTemp = m_lData & ((1<<m_iFilled)-1);
		m_iFilled = 0;
		lTemp <<= iLeft;
		return lTemp + read(iLeft);
	}
}
