/*
	Smooth Palette fade routines 0.13 for GCC 
	made by Ismo Horppu on 1996 - 1997
*/

#include <stdio.h>
#include <dpmi.h>
#include "ct2pal.h"
#include "types.h"
#include "ct2egen.h"
#include <math.h>
#include <stdlib.h>
#include "rpal.h"

void change_fadespeed (WORD new_speed)
{
	WORD c;

	if (new_speed > 64) new_speed = 64;
	if (new_speed < 1) new_speed = 1;

	for (c = 0; c < 768; c++){
		palstep[c] = (palstep[c] * new_speed) >> 6;
	}

	fade_limit = (64 / new_speed) << 6;
}

void calc_step (void)
{
	WORD c;

	for (c = 0; c < 768; c++){
		palstep[c] = (WORD) xpalbuf[c];
	}
}

void makefake (void)
{
	WORD c;

	for (c = 0; c < 768; c++){
		fakexpalbuf[c] = xpalbuf[c] << 6;
	}
}

void update (void)
{
	static WORD c;

	if (uc >= fade_limit) return;

	if (fd == -1){
		for (c = 0; c < 768; c++){
			if (fakexpalbuf[c] - palstep[c] > 0) fakexpalbuf[c] -= palstep[c];
			else fakexpalbuf[c] = 0;
			xpalbuf[c] = (BYTE) (fakexpalbuf[c] >> 6);
		}
	}

	else if (fd == 1){
		for (c = 0; c < 768; c++){
			if (fakexpalbuf[c] + palstep[c] < 4096) fakexpalbuf[c] += palstep[c];
			else fakexpalbuf[c] = 4096;
			xpalbuf[c] = (BYTE) (fakexpalbuf[c] >> 6);
		}
	}

	uc++;
}

/*	
	duplicate the local palette
*/
void GrabPalette (void)
{
	int c;
	
	for (c = 0; c < PalEntries; c++){
		xpalbuf[c] = Palette[c];
	}
}

void InitFade (int dir, WORD speed, BYTE skip)
{
	int c;

	GrabPalette ();
	calc_step ();

	/*
		start from full colored screen
	*/
	if (dir == -1) makefake ();

	/*
		start from black
	*/
	else{
		for (c = 0; c < 768; c++){
			fakexpalbuf[c] = 0;
		}
	}

	fd = dir;
	change_fadespeed (speed);
}

void ChangeDir (int dir)
{
	fd = dir;
}

void UpdateFade (void)
{
	while (1){
		update ();

		if (uc >= fade_limit){
			uc = 0;
			return;
		}

		SetPalette (&xpalbuf[0]);
	}
}