#include "StdAfx.h"
#include "BitFile.h"

void BitFile::openOutput(char*name) 
{
	file=fopen(name,"wb");
	rack=0;
	mask=0x80;		
	cb=0;
}

void BitFile::openOutput(FILE*f) 
{
	file=f;
	rack=0;
	mask=0x80;
	cb=0;
}

void BitFile::openInput(char*name) 
{
	file=fopen(name,"rb");
	rack=0;
	mask=0x80;
	cb=0;
}

void BitFile::openInput(FILE*f) 
{
	file=f;
	rack=0;
	mask=0x80;
	cb=0;
}

void BitFile::closeOutput() 
{
	if(mask!=0x80)
	{
		putc(rack,file);
		cb++;		
		return;
	}
	// fclose(file);
}

void BitFile::closeInput() 
{
	// fclose(file);
}

void BitFile::outputBit(int bit) 
{
	if(bit)
		rack|=mask;
	mask>>=1;
	if(mask==0) 
	{
		putc(rack,file);		
		rack=0;
		mask=0x80;
		cb++;
	}
}

void BitFile::outputBits(unsigned long code,int count) 
{
	unsigned long masque;
	masque=1L << (count-1);

	while(masque !=0) 
	{
		if(masque & code)
			rack|=mask;
		mask >>= 1;

		if(mask==0) 
		{
			putc(rack,file);			
			rack=0;
			mask=0x80;
			cb++;
		}
		
		masque>>=1;
	}
}

int BitFile::inputBit() 
{
	int value;
	if(mask==0x80) 
	{
		rack=getc(file);
		cb++;
		if(rack==EOF)
			return -1; // erreur;
	}
	
	value=rack & mask;
	mask>>=1;
	if (mask==0) 
		mask=0x80;

	return (value ? 1: 0 );
}

int BitFile::inputBits(int bit_count) 
{
	unsigned long masque;
	unsigned long return_value;
	masque=1L << (bit_count -1);
	return_value=0;

	while(masque != 0) 
	{
		if(mask==0x80) 
		{
			rack=getc(file);
			cb++;
		}
		
		if(rack & mask)
			return_value|=masque;
		
		masque>>=1;
		mask>>=1;
		
		if(mask==0)
			mask=0x80;
	}
	return return_value;
}