/* nowload.c
 * Larry W. Allen	MIT-LCS-DCS		10/6/83
 *
 * This program downloads a .ldb file to a serial line attached to a
 * Now Machine.
 * Calling sequence:
 *	nowload file #terminal [+baudrt]
 */

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

#define	LOADCMD		'l'			/* load cmd char for Now */
#define	BLKSIZ		0777			/* for printing stars... */
#define	putctr(c, f)	{ if (trace) fprintf(stderr, "%03x", c); \
			  putc(c, f); }

FILE	*now;
FILE	*filin;
int	nowno;
char	fname[128];

char	nowname[128] =	"/dev/tty";		/* base tty name */
int	baud =		9600;
int	trace = 0;


int	baudtab[] = {	9600, B9600,
			4800, B4800,
			2400, B2400,
			1800, B1800,
			1200, B1200,
			 600, B600,
			 300, B300,
			 200, B200,
			 150, B150,
			 134, B134,
			 110, B110,
			  75, B75,
			  50, B50,
			   0
			};


struct	sgttyb	TTYCmd = {		/* New line, no foreign hold */
				0,	/* IBAUD - set at init time */
				0,	/* OBAUD - " */
				0,	/* ERASEC - set from old mode */
				0,	/* KILLC - set from old mode */
				EVENP|ODDP|RAW, /* flags */
				};
struct	sgttyb	OTTYCmd;		/* old tty mode for restoring */

main(argc, argv)
char	*argv[];

{	int		argn;
	register	char	*p;
	register	int	c;
	register	i;

	if ((argc < 3) || (argc > 5))
		argerr();

	if (argv[2][0] != '#')
		argerr();
	strcat(nowname, &argv[2][1]);

	argn = 3;
	while (argn < argc) {
		p = argv[argn++];
		if (*p == '+') {
			baud = atoi(++p);
			continue;
		} else if (*p == '-' && *++p == 't') {
			trace++;
			continue;
		}
		argerr();
		}

	
	getbaud();
	getfil(argv[1]);


	ioctl(nowno, TIOCGETP, &OTTYCmd);
	ioctl(nowno, TIOCSETP, &TTYCmd);

	putctr(LOADCMD, now);
	fflush(now);

	fprintf(stderr, "\n\nStarting load of %s\n\n", fname);
	i = 0;

	while ((c = getc(filin)) != EOF) {
		putctr(c, now);
		if ((++i & BLKSIZ) == 0)
			if (trace)
				putc('\n', stderr);
			else
				putc('*', stderr);
		}

	fflush(now);
	ioctl(nowno, TIOCSETP, &OTTYCmd);
	fprintf(stderr, "\n\nLoad of %s complete\n", fname);

	fclose(filin);
	fclose(now);
}


getbaud()

{	register	*baudp;

	baudp = baudtab;
	for (;;) {
		if (*baudp == 0) {
			printf("\nUnknown baud rate %d\n", baud);
			exit(1);
			}
		if (*baudp++ == baud) {
			TTYCmd.sg_ispeed = *baudp;
			TTYCmd.sg_ospeed = *baudp;
			break;
			}
		baudp++;
		}
}


getfil(filnm)
char	*filnm;

{	register	char	*p, *q;
	char		*oldnm;

	now = fopen(nowname, "w");
	if (now == NULL) {
		fprintf(stderr, "\nCan't open Now output %s\n", nowname);
		exit();
		}
	nowno = fileno(now);
	setbuf(now, NULL);

	q = fname;
	for (p = filnm; *p != '\0'; *q++ = *p++);
	oldnm = q;
	for (p = ".ldb"; *p != '\0'; *q++ = *p++);

	if ((filin = fopen(fname, "r")) != NULL)
		return;
	*oldnm = '\0';
	if ((filin = fopen(fname, "r")) != NULL)
		return;

	fprintf(stderr, "\nCan't find file %s\n", filnm);
	exit();
}


argerr()

{		fprintf(stderr, "\n>nowload <filename> <#x> {+spd}\n");
		exit(1);
}
