/*-
 * Copyright (c) 2001
 * Tatsuya Kudoh(CDR/TK),ROYALPANDA.    All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 */

#include<stdlib.h>
#include<stdio.h>
#include<sys/bios.h>

#include"ks.h"
#include"malloc.h"

#pragma noregalo

/*
** Tick timer
*/

#define relative_time(t,base)	((int)((unsigned)(t) - (unsigned)(base)))

static unsigned Tick;		/* current tick count */	



/*
** memory block manager
*/

#define MAX_GARBAGE_SIZE	1024

static KSMemoryBlockManager *MemoryBlockManagers = NULL;
static int GarbageSize = 0;


void KSSetMemoryBlockManager( KSMemoryBlockManager *p, int block_size )
{
	p->next = MemoryBlockManagers;
	p->free_block_list = NULL;
	p->block_size = block_size;
	MemoryBlockManagers = p;
}


void KSCleanMemoryBlockManager( void )
{
	KSMemoryBlockManager *mp;
	void *p,*q;

#if 1
	mp = MemoryBlockManagers;
	while( mp != NULL ){
		p = mp->free_block_list;
		while( p != NULL ){
			q = p;
			p = *(void**)p;
			free(q);
		}
		mp->free_block_list = NULL;
		mp = mp->next;
	}
	GarbageSize = 0;
#endif
}


void *KSAllocateMemoryBlock( KSMemoryBlockManager *p )
{
	void *q;
#if 1
	if( p->free_block_list == NULL ){
		q = malloc(p->block_size);
		if( q == NULL ){
			KSCleanMemoryBlockManager();
			q = malloc(p->block_size);
		}
	}else{
		q = p->free_block_list;
		p->free_block_list = *(void**)q;
		GarbageSize -= p->block_size;
	}
#else
	q = malloc(p->block_size);
#endif
	if( q == NULL )
		KSWriteStringToConsole("Out Of\nMemory\n\n");

	return q;

	
}


void *KSFreeMemoryBlock( KSMemoryBlockManager *p, void *block )
{
#if 1
	if( block == NULL )
		return;

	if( GarbageSize + p->block_size > MAX_GARBAGE_SIZE ){
		KSCleanMemoryBlockManager();
		free(block);
		return;
	}
	*(void**)block = p->free_block_list;
	p->free_block_list = block;
	GarbageSize += p->block_size;
#else
	free(block);
#endif
}


void *KSAllocate( int size )
{
	void *p;

	p = malloc(size);
#if 1
	if( p == NULL ){
		KSCleanMemoryBlockManager();
		p = malloc(size);
	}
#endif
	if( p == NULL )
		KSWriteStringToConsole("Out Of\nMemory\n");
	return p;
}


void KSFree( void *p )
{
#if 1
	free(p);
#endif
}


/*
** Msg queue
*/

static KSMsg *MsgQueueIn = NULL;
static KSMsg *MsgQueueOut = NULL;
static KSMemoryBlockManager MsgMemMgr;


/*
** exit flag
*/

static int ExitFlag = 0;	/* set 1 to exit event loop */


/*
** init
*/

void KSInitialize( void )
{
	KSSetMemoryBlockManager(&MsgMemMgr,sizeof(KSMsg));

	Tick = sys_get_tick_count();

	KSDrawInitialize();
	KSInitializeKeyboard();
	KSInitializeConsole();
	KSInitializeReggFEP();
	KSInitializeLineInput();

	ExitFlag = 0;
}


void KSSetExitFlag( void )
{
	ExitFlag = 1;
}


KSMsg *KSAllocateMsg( void )
{
	return (KSMsg*)KSAllocateMemoryBlock(&MsgMemMgr);
}


void KSSendMsg( KSMsg *msg )
{
	msg->null.next = NULL;
	if( MsgQueueIn == NULL ){
		MsgQueueIn = msg;
		MsgQueueOut = msg;
	}else{
		MsgQueueIn->null.next = msg;
		MsgQueueIn = msg;
	}
}


static void free_msg( KSMsg *msg )
{
	if( msg->type & 0x80 ){
		switch( msg->type ){
		case KS_MSG_TEXT:
			if( msg->text.text != NULL )
				KSFree(msg->text.text);
			break;

		case KS_MSG_PACKED_TEXT:
			if( msg->packed_text.text != NULL )
				KSFree(msg->packed_text.text);
			break;
		}
	}
	KSFreeMemoryBlock(&MsgMemMgr,msg);
}


void KSMainLoop( void )
{
	unsigned t;

	KSMsg *q,*msg;

	t = Tick;
	while( !ExitFlag ){
		while( MsgQueueOut != NULL ){
			q = MsgQueueOut;
			MsgQueueOut = NULL;
			MsgQueueIn = NULL;
			while( q != NULL ){
				msg = q;
				q = q->null.next;
				if( msg->null.receiver == NULL
					    || msg->null.receiver(msg) == 0 )
					free_msg(msg);
			}
		}

		Tick = sys_get_tick_count();
		if( Tick != t ){
			t = Tick;
			if( KSKeyboard(Tick) < 0 )
				/* fatal error */ ;
			KSBlinkCursor();
		}
	}
}
