
/* This is a program to feed a .ldb format program into the qbus 68000 card.
 * It simply reads the file in and issues the appropriate commands to the
 * ROM monitor. It is designed for the MINITOR monitor.
 */

#include	<stdio.h>
#include	<sgtty.h>

#define	mgetc(fd)	(getc(fd) & 0377)

char	*line_name = "/dev/tty--";
/*char	*line_name = "zyxwfoob--";*/

main(argc, argv)
int	argc;
char	*argv[];
{
    FILE	*oline, *iline, *file;
    unsigned long	loadpt, start;
    int		i, il, olineno, ilineno, number, count;
    struct sgttyb	otty_mode, ntty_mode;

    if (argc < 3 || argc > 3) {
	printf("Usage: %s tty-line file\n", argv[0]);
	exit(1);
    }
    
    line_name[8] = argv[1][0];
    line_name[9] = argv[1][1];
    if ((oline = fopen(line_name, "w")) == NULL) {
	printf("Error: Couldn't open %s for write\n", line_name);
	exit(1);
    }
    
    if ((iline = fopen(line_name, "r")) == NULL) {
	printf("Error: Couldn't open %s for read\n", line_name);
	fclose(oline);
	exit(1);
    }
    
    if ((file = fopen(argv[2], "r")) == NULL) {
	printf("Error: Couldn't open %s for read\n", argv[2]);
	fclose(oline);
	fclose(iline);
	exit(1);
    }
    
    if (getc(file) != 1 || getc(file) != 0) {
	printf("Error: File %s not in .ldb format\n", argv[2]);
	fclose(file);
	fclose(oline);
	fclose(iline);
	exit(1);
    }
    
    count = mgetc(file) << 24;
    count |= mgetc(file) << 16;
    count |= mgetc(file) << 8;
    count |= mgetc(file);
    count -= 14;	/* subtract the number of bytes in the header */
    loadpt = mgetc(file) << 24;
    loadpt |= mgetc(file) << 16;
    loadpt |= mgetc(file) << 8;
    loadpt |= mgetc(file);
    start = mgetc(file) << 24;
    start |= mgetc(file) << 16;
    start |= mgetc(file) << 8;
    start |= mgetc(file);
    
    printf("count = %x\nloadpt = %x\nstart = %x\n", count, loadpt, start);
    
    olineno = fileno(oline);
    ilineno = fileno(iline);
    ioctl(ilineno, TIOCGETP, &otty_mode);
    ntty_mode.sg_ispeed = otty_mode.sg_ispeed;
    ntty_mode.sg_ospeed = otty_mode.sg_ospeed;
    ntty_mode.sg_erase = otty_mode.sg_erase;
    ntty_mode.sg_kill = otty_mode.sg_kill;
    ntty_mode.sg_flags = EVENP|ODDP|RAW;
    ioctl(ilineno, TIOCSETP, &ntty_mode);

    ioctl(olineno, TIOCSBRK, 0);
    for (i = 0; i < 0500; i++);	/* number 0500 is for 9600 baud, crock! */
    ioctl(olineno, TIOCCBRK, 0);

    il = 0;
    while (count > 0) {
	while (getc(iline) != '.') ;
	putchar('.');
	if (il++ > 79) {
		il = 0;
		putchar('\n');
	}
	fflush(stdout);
	fprintf(oline, "0%x ", loadpt);
	for (i = 0; i < 16; i++) {
	    number = mgetc(file) << 8;
	    number |= mgetc(file);
	    fprintf(oline, "%x ", number);
	    loadpt += 2;
	    if ((count -= 2) < 0) break;
	}
	putc('\r', oline);
	fflush(oline);
    }
    
/* At this point should start the program if start is not equal to FFFFFF. */

    printf("Done. Closing files\n");
    ioctl(ilineno, TIOCSETP, &otty_mode);
    fclose(file);
    fclose(oline);
    fclose(iline);
}
