/* Installs a new operating system */

#include <libraries/dos.h>

#define RAMBASE	(0x400)
#define MAXSIZE (196608)

void	Switchoff();
void	DMAoff();
void	Intsoff();
void	Jumpzero();
void	foad();
void	pause();

main()
{
	char	*image;
	int	imfile, a=0, pos, one;

	if( ((void*)main<(void*)MAXSIZE) ||
	    (&image < (char**)MAXSIZE) )
	{
		printf("go is in its own way\n");
		return;
	}

	OpenLibrary( "graphics.library", 0 );

	do
	{
		if( (image=(char*)malloc( MAXSIZE )) == 0 )
			foad( "Cannot allocate memory for image");
	} while( image<(char*)MAXSIZE );

	if( (imfile=Open("kerim",MODE_OLDFILE)) <= 0 )
	{
		free( image );
		foad( "Cannot open image file" );
	}

	pos=0;
	while( one=Read( imfile, image+pos, MAXSIZE ) )
		pos+=one;

	Close( imfile );

	printf("Loaded %i bytes... about to be reborn\n",pos);

	pause(50);	/* Give everything time to stop */
	Switchoff();
	pause(25);	/* For safety */
	Intsoff();
	pause(25);	/* For safety */
	DMAoff();

	for(a=0;a<MAXSIZE;a++)
		*(char*)(RAMBASE+a)=*(image+a);

	Jumpzero( RAMBASE );
}

void Switchoff()
{
	Forbid();
}

void Intsoff()
{
	Disable();
}

void DMAoff()
{
	*(short*)0xdff096=(short)0x0200;
}

void pause( period )
int period;
{
	int a;

	for(a=0;a<period;a++)
		WaitTOF();
}

void foad( msg )
{
	printf( "**** Fatal boot error\n%s\n****\n", msg );
	exit();
}

