#include "commun.h"

const unsigned char *coeffs;

void ChargePalette(const unsigned short *palette, unsigned short *dest, unsigned char fin)
{
//	s16 rouge, vert, bleu, temp;
	u16 x;

	for (x = 0; x < fin; x++)
	{

		/*		temp=palette[x];
		bleu=(temp&0x7C00)>>10;
		vert=(temp&0x3E0)>>5;
		rouge=(temp&0x1F);
		dest[x]=RVB(rouge,vert,bleu);*/
		dest[x] = palette[x];
	}
}

#define REG_STOPCNT * (volatile unsigned char *) 0x4000301
void AttendVSync()
{
	while (REG_VCOUNT >= 160);
	while (REG_VCOUNT < 160);

	/*    while (REG_VCOUNT>=160) REG_STOPCNT=0<<7;
	while (REG_VCOUNT<160) REG_STOPCNT=0<<7;*/
}

void AttendVSyncRapide()
{
	while (REG_VCOUNT >= 160);
	while (REG_VCOUNT < 160);
}

void CopieDMA(void *source, void *dest, unsigned int nbval, unsigned int mode)
{
	if (mode == DMA_16im || mode == DMA_32im)
	{
		// Attend que le canal DMA soit libre
		while (REG_DMA3CNT & DMA_ENABLE);
		REG_DMA3SAD = (unsigned int) source;
		REG_DMA3DAD = (unsigned int) dest;
		REG_DMA3CNT = nbval | mode;
	}
}

void CopieDMA0(void *source, void *dest, unsigned int nbval, unsigned int mode)
{
	if (mode == DMA_16im || mode == DMA_32im)
	{
		// Attend que le canal DMA soit libre
		while (REG_DMA0CNT & DMA_ENABLE);
		REG_DMA0SAD = (unsigned int) source;
		REG_DMA0DAD = (unsigned int) dest;
		REG_DMA0CNT = nbval | mode;
	}
}

void MemSet(void *source, void *dest, unsigned int nbval, unsigned int mode)
{
	if (mode == DMA_16im || mode == DMA_32im)
	{
		// Attend que le canal DMA soit libre
		while (REG_DMA3CNT & DMA_ENABLE);
		REG_DMA3SAD = (unsigned int) source;
		REG_DMA3DAD = (unsigned int) dest;
		REG_DMA3CNT = nbval | mode | 0x0100 << 16;
	}
}

void _memset(void *dest, void *source, unsigned int nbval)
{
	u32 reg_dma;
	nbval >>= 1;
	// Attend que le canal DMA soit libre
	while (REG_DMA3CNT & DMA_ENABLE);
	REG_DMA3SAD = (unsigned int) source;
	REG_DMA3DAD = (unsigned int) dest;
	reg_dma = nbval | DMA_16im | 0x0100 << 16;
	REG_DMA3CNT = reg_dma;
}

void MemMove16bits(void *dest, void *source, unsigned int nbval)
{
	u32 reg_dma = 0;

	nbval >>= 1;

	// Attend que le canal DMA soit libre
	while (REG_DMA3CNT & DMA_ENABLE);

	if (dest <= source)
	{
		REG_DMA3SAD = (unsigned int) source;
		REG_DMA3DAD = (unsigned int) dest;
		reg_dma = nbval | DMA_16im;
	}
	else
	{
		REG_DMA3SAD = (unsigned int) ((u16 *) source + nbval - 1);
		REG_DMA3DAD = (unsigned int) ((u16 *) dest + nbval - 1);
		reg_dma = nbval | DMA_16im | 0x80 << 16 | 0x20 << 16;
	}

	REG_DMA3CNT = reg_dma;
}

/*extern MEM_FUNC_IN_IWRAM double pow _PARAMS((double, double));

void CreeTablesGamma(double gamma)      {
int y;

for (y=0;y<32;y++)
coeffs[y]=(unsigned char)(31.0*pow((y/31.0),gamma));
}*/

void InitTimers()
{
	//Stoppe le timer
	gbaSetTimerControl(1, 0);
	//Le remet ŕ zéro
	gbaSetTimerValue(1, 0);
	//65 kHz & démarrer
	gbaSetTimerControl(1, TIMER_SPEED(2) | TIMER_ENABLED);
}

void NouvelleTrame()
{
	gbaSetTimerControl(1, 0);
	gbaSetTimerValue(1, 0);
	gbaSetTimerControl(1, TIMER_SPEED(2) | TIMER_ENABLED);
}
