/*
 * Copyright (C) 2009, 2010 by Nicole Faerber <nicole.faerber@dpin.de>
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version
 * 2 of the License, or (at your option) any later version.
 *
 */

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

#include "bitstream.h"

static unsigned char *_BITBUF;
static unsigned int _BITPOS;
static unsigned int _BUFLEN;

void printbits(unsigned int val)
{
unsigned char i=0;

	while (i<32)
		if (val & (1<<(31-i++)))
			printf("1 ");
		else
			printf("0 ");
//	printf("\n");
}

void printbuf_head(unsigned char *buf)
{
	//printbits(buf[3]<<24 | buf[2]<<16 | buf[1]<<8 | buf[0]);
	printbits(buf[0]<<24 | buf[1]<<16 | buf[2]<<8 | buf[3]);
}

unsigned int bitstream_get_bits(unsigned char *data, unsigned int bitOffset, unsigned int numBits)
{
unsigned int val;
unsigned int mask = (1 << numBits) - 1;

	data += ((bitOffset / 8) -3);
	val = *((int *)data);
//	printf("0x%08x ", val);

	val = val << (bitOffset % 8);
//	printf("0x%08x ", val);

	val = val >> (32-numBits);
//	printf("0x%08x %d ", val, (32-numBits));

	val &= mask;
//	printf("0x%08x\n", val);

return val;
}

int bitstream_bits_remaining(void)
{
	return (_BUFLEN - _BITPOS);
}

unsigned int bitstream_get_next_bits(unsigned int nbits)
{
unsigned int res;

	res = bitstream_get_bits(_BITBUF, _BITPOS, nbits);
	_BITPOS += nbits;

	return res;
}

void bitstream_start(unsigned char *buf, unsigned int len)
{
	_BITBUF = buf;
	_BITPOS = 0;
	_BUFLEN = len;
}


