/*
 *  Hex loader program.  Sends an ASCII file out the serial port to the
 *  loader running in the TNC-2 KISS loader ROM.  Use this rather than
 *  just "COPY TNC2KISS.HEX to SER:" so we don't have to depend on what
 *  the preferences baud rate for the serial port is set to.
 *
 *  Copyright (C) 1987
 *  Louis A. Mamakos
 *
 *  For non-commercial use only.  May not be sold, or included in any other
 *  product or collection of software that is sold for profit.
 */

#include <exec/types.h>
#include <functions.h>		/* for Manx Aztec C, get func returns */
#include <exec/nodes.h>
#include <exec/lists.h>
#include <exec/ports.h>
#include <exec/devices.h>
#include <exec/io.h>
#include <devices/serial.h>
#include <libraries/dos.h>
#include <libraries/dosextens.h>
#include <stdio.h>

#ifndef	DEFFILE
#define	DEFFILE	"tnc2kiss.hex"
#endif

#ifndef	DEFBAUD
#define	DEFBAUD	4800
#endif

struct IOExtSer serout;
struct MsgPort *seroutp;
struct	FileHandle	*hexfile;
char	buffer[500];
extern	int Enable_Abort;
int	baud = DEFBAUD;

main(argc, argv)
	int argc;
	char **argv;
{
	register long totlen = 0;
	register long len;
	
	strcpy(buffer, DEFFILE);
	if ((argc > 1) && ((baud = atoi(argv[1])) > 0)) {
		serout.io_Baud = baud;
		argc--; argv++;
		printf("Loading at %d baud\n", baud);
	}
	if (argc > 1)
		strcpy(buffer, argv[1]);

	hexfile = Open(buffer, MODE_OLDFILE);

	Enable_Abort = 0;

	if (hexfile == 0L) {
		printf("Can't open file '%s'\n", buffer);
		exit(1);
	}

	if ((seroutp = CreatePort(0L, 0L)) == NULL) {
		printf("Can't create serial input port");
		Close(hexfile);
		exit(2);
	}
	/*
	 * Open serial device.
	 */
	serout.io_SerFlags = SERF_XDISABLED | SERF_RAD_BOOGIE;  /* ? */
	serout.io_Status = 0;
	serout.io_Baud = baud;
	if (OpenDevice("serial.device", 0L, &serout, 0L) != 0) {
		printf("Can't open serial device");
		DeletePort(seroutp);
		Close(hexfile);
		exit(2);
	}
	serout.IOSer.io_Message.mn_ReplyPort = seroutp;
	serout.IOSer.io_Data = (APTR) buffer;
	serout.IOSer.io_Length = 0;
	serout.IOSer.io_Command = CMD_WRITE;
	serout.IOSer.io_Flags = 0;
	serout.io_SerFlags = SERF_XDISABLED | SERF_RAD_BOOGIE;
	serout.io_Baud = baud;
	serout.IOSer.io_Command = SDCMD_SETPARAMS;

	if (DoIO(&serout))
		printf("SETPARMS failed\n");

	serout.IOSer.io_Command = CMD_WRITE;
	serout.IOSer.io_Data = (APTR) buffer;
	while ((len = Read(hexfile, buffer, (ULONG) sizeof(buffer))) > 0) {
		serout.IOSer.io_Length = len;
		if (DoIO(&serout))
			printf("Serial write failed %ld\n",
				serout.IOSer.io_Error);
		totlen += len;
		if (Chk_Abort()) {
			printf("Hex load aborted!\n");
			break;
		}
	}
	printf("Wrote %ld bytes\n", totlen);
	Close(hexfile);
	CloseDevice(&serout);
	DeletePort(seroutp);
}

