/*
 * 5799-WZQ (C) COPYRIGHT IBM CORPORATION 1988
 * LICENSED MATERIALS - PROPERTY OF IBM
 * REFER TO COPYRIGHT INSTRUCTIONS FORM NUMBER G120-2083
 */
/* $Header:loadboot.c 12.0$ */
/* $ACIS:loadboot.c 12.0$ */
/* $Source: /ibm/acis/usr/sys/os2code/RCS/loadboot.c,v $ */

/*
 * Copyright University of Southern California, 1988
 */

#include <malloc.h>
#include "pctype.h"
#include "pcparam.h"
#include "rb.h"
#include "aout.h"
#include "os2data.h"

long	filelength();		/* has to be declared as long */

struct AOUT     adot = {0};

#define XFERBUF (1024 * 10)
static char	local_buffer[XFERBUF];
static char	*sbuff_dio = local_buffer; /* local buffer */

u_long
loadboot(fd)
	u_short         fd;
{
	long            block, addr = 0;
	u_short         xblock;
	int             r;
	u_char		*cp;
	int		i,j,k;

	block = filelength(fd) - sizeof(struct AOUT);

	cp = (u_char *) &adot;

	if ((r = read(fd, cp, sizeof(struct AOUT))) != sizeof(struct AOUT))
		fatal("Error reading exec header",0);


	/* Take out (long)'s and redefine struct aout to avoid
	   sing extension problem */

	adot.a_entry = exchl(adot.a_entry) & 0x00ffffff;
	adot.a_text = exchl(adot.a_text);
	adot.a_data = exchl(adot.a_data);
	adot.a_bss = exchl(adot.a_bss);
	adot.a_magic = exchl(adot.a_magic);
	adot.a_syms = exchl(adot.a_syms);
	adot.a_trsize = exchl(adot.a_trsize);
	adot.a_drsize = exchl(adot.a_drsize);

	if(adot.a_magic != 0407 && adot.a_magic != 0410 && 
						adot.a_magic !=0413)
	{
		char buf[100];
		sprintf(buf,"Bad Magic number 0%o \n", adot.a_magic);
		fatal(buf,1);
	}

	addr = adot.a_entry;

	while (block > 0L)
	{
		if (block > XFERBUF)
			xblock = XFERBUF;
		else
			xblock = (u_short) block;

		if ((r = read(fd, sbuff_dio, xblock)) != xblock)
		{
			fatal("Error reading boot file",1);
		}

		if (moveout(addr, (char far *) sbuff_dio, xblock) < 0){
			fatal("Error writing bootfile to Co-processor",1);
		}

		block -= xblock;
		addr += xblock;
	}
	return ((u_long) adot.a_entry);
}
