/// @file mtfll.cpp
/// Move to front encoding
///
/// @remarks
/// Experimental move to front encoding using a linked list
///
/// @author loco
/// @date   2003.08.14
///
///

#include "mtfll.hpp"

#include <iomanip>
using namespace std;

mtfllCompressor GloballyInstantiated_mtfll(true);

mtfllCompressor::mtfllCompressor(bool registerme)
	:OctaneCompressor(registerme)
{
	if (registerme)CompressorManager_SingletonInsurer managerinsurance(this);
}

bool mtfllCompressor::DoProtectedCompress(bitreader &s, bitwriter &d)
{
	unsigned int array[256], pointers[256];

	for (unsigned int i = 0; i < 256; i++) array[i] = pointers[i] = i;

	while (!s.empty())
	{
		unsigned char b = s.get_byte();
		d.put_byte((unsigned char)pointers[b]);

		if (pointers[b])
		{
			for (unsigned char c = (unsigned char)pointers[b]; c; c--)
			{
				array[c] = array[c-1];
				pointers[array[c]]++;
			}
			array[0] = b;
			pointers[b] = 0;
		}
	}
	return true;
}

bool mtfllCompressor::DoProtectedDecompress(bitreader &s, bitwriter &d)
{
	unsigned int array[256], pointers[256];

	for (unsigned int i = 0; i < 256; i++) array[i] = pointers[i] = i;

	while (!s.empty())
	{
		unsigned char b = (unsigned char)array[s.get_byte()];
		d.put_byte(b);

		if (pointers[b])
		{
			for (unsigned char c = (unsigned char)pointers[b]; c; c--)
			{
				array[c] = array[c-1];
				pointers[array[c]]++;
			}
			array[0] = b;
			pointers[b] = 0;
		}
	}
	return true;
}
