
#ifndef ENTENC_H
#define ENTENC_H

#include "entcode.h"

#ifndef HW_CODESIZE
void rc_enc_init_1(ec_enc *_this,unsigned char *_buf,unsigned short _size);
#endif
void rc_encode_1(ec_enc *_this,unsigned short _fl,unsigned short _fh,unsigned short _ft);
void rc_enc_bit_logp_1(ec_enc *_this,short _val,unsigned short _logp);
void rc_encode_bin_1(ec_enc *_this,unsigned short _fl,unsigned short _fh,unsigned short _bits);
void rc_enc_icdf_1(ec_enc *_this,short _s, const unsigned char *_icdf,unsigned short _ftb);





static int ec_write_byte_1(ec_enc *_this,unsigned _value)
{
	if(_this->offs+_this->end_offs>=_this->storage) return -1;
	_this->buf[_this->offs++]=(unsigned char)_value;
	return 0;
}

static int rc_write_byte_at_end_1(ec_enc *_this,unsigned _value)
{
	if(_this->offs+_this->end_offs>=_this->storage)return -1;
	_this->buf[_this->storage-++(_this->end_offs)]=(unsigned char)_value;
	return 0;
}



#ifndef HW_CODESIZEx   // (º¸·ù)
static void rc_enc_carry_out_1(ec_enc *_this,int _c)
#else
void rc_enc_carry_out_1(ec_enc *_this,int _c)
#endif
{
	if(_c!=EC_SYM_MAX)
	{
		int carry;
		carry=_c>>EC_SYM_BITS;
		if(_this->rem>=0)_this->error|=ec_write_byte_1(_this,_this->rem+carry);
		if(_this->ext>0)
		{
			unsigned sym;
			sym=(EC_SYM_MAX+carry)&EC_SYM_MAX;
			do{
				_this->error|=ec_write_byte_1(_this,sym);
			}while(--(_this->ext)>0);
		}
		_this->rem=_c&EC_SYM_MAX;
	}
	else _this->ext++;
}


static void rc_enc_normalize_1(ec_enc *_this)
{
	/*If the range is too small, output some bits and rescale it.*/
	while(_this->rng<=EC_CODE_BOT)
	{
		rc_enc_carry_out_1(_this,(int)(_this->val>>EC_CODE_SHIFT));
		/*Move the next-to-high-order symbol into the high-order position.*/
		_this->val=(_this->val<<EC_SYM_BITS)&(EC_CODE_TOP);
		_this->rng<<=EC_SYM_BITS;
		_this->nbits_total+=EC_SYM_BITS;
	}
}

/*
static void rc_enc_icdf_1(ec_enc *_this,short _s,const unsigned char *_icdf,unsigned short _ftb)
{
	unsigned int r;
	r=_this->rng>>_ftb;
	if(_s>0)
	{
		_this->val+=_this->rng-MUL(r,_icdf[_s-1]);
		_this->rng=MUL(r,_icdf[_s-1]-_icdf[_s]);
	}
	else
		_this->rng-=MUL(r,_icdf[_s]);
	rc_enc_normalize_1(_this);
}
*/

void rc_enc_uint_1(ec_enc *_this,unsigned int _fl,unsigned int _ft);
void rc_enc_bits_1(ec_enc *_this,unsigned int _fl,unsigned _ftb);
void rc_enc_done_1(ec_enc *_this);



#endif
