/* -*- mode: C; c-basic-offset: 4; indent-tabs-mode: nil -*- */
// vim: expandtab:ts=8:sw=4:softtabstop=4:
///////////////////////////////////////////////////////////////////////////////
//
/// \file       price_tablegen.c
/// \brief      Probability price table generator
///
/// Compiling: gcc -std=c99 -o price_tablegen price_tablegen.c
///
//  Authors:    Igor Pavlov
//              Lasse Collin
//
//  This file has been put into the public domain.
//  You can do whatever you want with this file.
//
///////////////////////////////////////////////////////////////////////////////

#include <inttypes.h>
#include <stdio.h>
#include "range_common.h"
#include "price.h"


static uint32_t rc_prices[RC_PRICE_TABLE_SIZE];


static void
init_price_table(void)
{
	for (uint32_t i = (UINT32_C(1) << RC_MOVE_REDUCING_BITS) / 2;
			i < RC_BIT_MODEL_TOTAL;
			i += (UINT32_C(1) << RC_MOVE_REDUCING_BITS)) {
		const uint32_t cycles_bits = RC_BIT_PRICE_SHIFT_BITS;
		uint32_t w = i;
		uint32_t bit_count = 0;

		for (uint32_t j = 0; j < cycles_bits; ++j) {
			w *= w;
			bit_count <<= 1;

			while (w >= (UINT32_C(1) << 16)) {
				w >>= 1;
				++bit_count;
			}
		}

		rc_prices[i >> RC_MOVE_REDUCING_BITS]
				= (RC_BIT_MODEL_TOTAL_BITS << cycles_bits)
				- 15 - bit_count;
	}

	return;
}


static void
print_price_table(void)
{
	printf("/* This file has been automatically generated by "
			"price_tablegen.c. */\n\n"
			"#include \"range_encoder.h\"\n\n"
			"const uint8_t lzma_rc_prices["
			"RC_PRICE_TABLE_SIZE] = {");

	const size_t array_size = sizeof(lzma_rc_prices)
			/ sizeof(lzma_rc_prices[0]);
	for (size_t i = 0; i < array_size; ++i) {
		if (i % 8 == 0)
			printf("\n\t");

		printf("%4" PRIu32, rc_prices[i]);

		if (i != array_size - 1)
			printf(",");
	}

	printf("\n};\n");

	return;
}


int
main(void)
{
	init_price_table();
	print_price_table();
	return 0;
}
