/*
 * esa0.c
 * Mainline.
 */
#include <stdio.h>
#include "esa.h"

/*
 * This is the mainline.
 * It scans the command line,
 * collects up a source file,
 * sets option flags and calls
 * the assembler proper.
 */
main(argc, argv)
char *argv[];
{
	register int i, c;
	register char *p;
	char *file;

	file = NULL;
	for(i=1; i<argc; ++i) {
		p = argv[i];
		if(*p++ == '-') {
			while(c = *p++)
				switch(c) {

				case 'l':
				case 'L':
					++lflag;
					break;

				case 'n':
				case 'N':
					++nflag;
					break;

				default:
					usage();
				}
		} else if(file != NULL)
			usage();
		else
			file = argv[i];
	}
	if(file == NULL)
		usage();
	assemble(file);
}

/*
 * Assemble a file.
 */
assemble(file)
char *file;
{
	char fn[40];

	name(fn, file, "esa", 0);
	if((src=fopen(fn, "r")) == NULL) {
		fprintf(stderr, "%s: cannot open.\n", fn);
		exit(1);
	}
	if(lflag) {
		name(fn, file, "lst", 1);
		if((lst=fopen(fn, "w")) == NULL) {
			fprintf(stderr, "%s: cannot create.\n", fn);
			exit(1);
		}
	}
	if(!nflag) {
		name(fn, file, "esb", 1);
		if((esb=fopen(fn, "w")) == NULL) {
			fprintf(stderr, "%s: cannot create.\n", fn);
			exit(1);
		}
	}
	for(pass=0; pass<2; ++pass) {
		rewind(src);
		lineno = 0;
		dot->s_type = S_ABS;
		dot->s_flag = SF_ASG;
		dot->s_value = 0;
		while(fgets(sbuf, src) != NULL) {
			++lineno;
			sptr = sbuf;
			cptr = cbuf;
			eptr = ebuf;
			asmline();
			if(pass) {
				outerrors();
				if(lflag)
					outlisting();
			}
		}
	}
	if(!nflag)
		cflush();
}

/*
 * If the user screws up, put out
 * a usage message.
 * Then quit.
 * Not much sense staying around.
 */
usage()
{
	fprintf(stderr, "Usage: esa [-l] [-n] file.\n");
	exit(1);
}

/*
 * Build RSX file names.
 * The mode argument is either 0
 * which means default, or 1 which
 * means replace with.
 */
name(fn, file, type, mode)
char *fn, *file, *type;
{
	register char *p1, *p2;
	register int c;

	p1 = fn;
	p2 = file;
	while((c = *p2++) && c!='.')
		*p1++ = c;
	if(mode == 0) {
		if(c == '.') {
			do {
				*p1++ = c;
			} while(c = *p2++);
		} else {
			*p1++ = '.';
			p2 = type;
			while(c = *p2++)
				*p1++ = c;
		}
	} else {
		*p1++ = '.';
		p2 = type;
		while(c = *p2++)
			*p1++ = c;
	}
	*p1 = '\0';
}
