// main-s.txt
//   public release som-v2   30 Dec 2004
//   public release som-v24 10 January 2007

//  system area  1 .. MAXSYS-1
//   1..80   tokstring-som
//   100	 CS base ads
//   101     mode ads
//   110..149 "inputfile"  som-string
//   150..199 "input.lst"  som-string
//   200..249 "input.obj"  som-string

enum
	100 cs_ads mode_ads
enum
	110 src_file
enum
	150 lst_file
enum
	200 obj_file

to parse | f e tk =
	setcdr im NIL		// clear im
	startlex
	lex
	while tok != tkEOF
		tk = tok
		f = top			// parse, throw away flag
		e = ypop
		if (tk == tkTO) | (tk == tkCOLON)
//			def = append def e
			genex e
		else
			im = append im e

to init_all =
	initSom
	init_list
	def = list newatom OPER tkBB
	im = list newatom OPER tkBB
	initkeysym
	initlex

//to report =
//	prints ">> CP " print CP space
//	prints "ysp " print ysp space
//	prints "DS " print array 0 space
//	countcell
//	countsym

to loadfile fn =
	FI = fopen fn 0
	cmode = 0
	parse
	fclose FI
//	report
	runimm im

to reloc disp | i k a v =
	for i 0 nxsym-1
		k = exsym[i]
		if (getType k) == tyGVAR
			a = getArity k
			v = getRef k			// refresh symtab
			setRef k v+disp
			if (a == VSTRING) | (a == VARRAY)
				M[v] = M[v] + disp	// reloc
	for i 1 CP-1
		k = CS[i] & 255
		if (k==icAds) | (k==icLd) | (k==icSt)
			a =  CS[i] >> 8
			putcode i k a+disp		// reloc

to outobj fn | ds =
	ds = array 0			// end of user ds
	reloc 1000-userDS
	FO = fopen fn 1
	fprint FO OBJ_SOM16 fnl
	outhead 1 CP-1
	outM CS 1 CP-1			// code
	outhead 1000 1000+ds-1-userDS
//	outhead userDS ds-1
	outM M userDS ds-1		// data
	dumpSym					// symbol table
	fclose FO

to outcode fn =
	FO = fopen fn 1
	showCode 1 CP-1
	fclose FO

// read-eval-print loop, stdin
to rep =
	while 1
		FI = 0		// stdin
		cmode = 2	// interactive
		printc 62	// >
		parse
		runimm im

// bind values between som.obj and interp.c
// through system area

to main =
	init_all
	M[cs_ads] = CS
	userDS = array 0		// start of user ds
	loadfile "lib2.som"
	if M[mode_ads] == 1		// mode 1 interact, 2 compile&run
		rep
	else
		loadfile src_file
		genfinal
//		showCode 1 CP-1
		nxsym = getExportSym exsym
		outobj obj_file
		outcode lst_file

// End
