/* util.c */

#include "mphead.h"

#define MINBUFSIZE	50000

unsigned bit_buf;
int bit_num;

int buf_size = MINBUFSIZE*4;

unsigned char *buf_point,*buf_check,*malloc();

static position;
static unsigned char *buf,*buf_end;

fill_bits()
{
	if (bit_num == 0) {
		bit_buf = buf_point[0]<<24 | buf_point[1]<<16 | buf_point[2]<<8 | buf_point[3];
		buf_point += 4;
		bit_num = 32;
		return;
	}
	if (bit_num <= 8) {
		bit_buf = bit_buf<<24 | buf_point[0]<<16 | buf_point[1]<<8 | buf_point[2];
		buf_point += 3;
		bit_num += 24;
		return;
	}
	if (bit_num <= 16) {
		bit_buf = bit_buf<<16 | buf_point[0]<<8 | buf_point[1];
		buf_point += 2;
		bit_num += 16;
		return;
	}
	bit_buf = bit_buf<<8 | *buf_point++;
	bit_num += 8;
}

fill_buf()
{
	int i,j;

	if (buf_point < buf_check)
		return;
	if (buf_point > buf_end) {
		write_2("buffer went bad\n");
		eexit();
	}
	i = buf_end - buf_point;
	j = (int)buf_point & 3;
	copy_memory(buf+j,buf_point,i);
	buf_point = buf+j;
	buf_end = buf_point+i;
	do {
		i = read(0,buf_end,buf+buf_size-buf_end);
		if (i == 0)
			break;
		if (i > 0) {
			position += i;
			buf_end += i;
		}
	} while (buf+buf_size > buf_end);
	buf_check = i ? buf_end-MINBUFSIZE : buf_end;
	memset(buf_end,0,buf+buf_size-buf_end);
}

init_util()
{
	buf = malloc(buf_size);
	position = 0;
	buf_check = buf_end = buf_point = buf;
	bit_buf = bit_num = 0;
	fill_buf();
}

unsigned
next_start_code()
{
	fill_buf();
	bit_num &= ~7;
	fill_bitsn(32);
	while ((bit_buf&0xffffff00) != 0x100) {
		bit_buf = bit_buf<<8 | *buf_point++;
		fill_buf();
	}
	return bit_buf;
}

get_ext_data()
{
	next_start_code();
}

get_extra_bit_info()
{
	while (fill_bitsn(9),get_bitsn(1)) {
		flush_bitsn(8);
		fill_buf();
	}
}
