* 8/27/91
*	program is now 1, accessory now 0.  Reverses the way things
*	would work. 
*
* 8/23/91
* NOTE:  progsize is set to 0 if .ACC or .WNX, so these can't be used
* for those type of programs.  This is because I don't want to assume
* the basepage is 256 bytes before the .ACC, but I guess that would be
* safe... 

STKSIZE	= 4*1024

		XREF	_main
		XREF	__initargcv
		XREF	_exit
		XDEF	stksize,__app,__base,progsize,stack
		XDEF	__argc,__argv,_errno,_seed,_environ

		SECTION TEXT
		
START:		lea	START,a5	;get the address of this code
		sub.l	#$100,a5	;a5 = ptr to basepage if .PRG or .WNX
		move.l	a5,__base	;store basepage ptr in base...
		cmp.l	#"XES",40(a5)	;is p_reserved = "XES"
		beq.s	.start_wnx	;no, so do .PRG startup code

		move.l	a0,d0			
		tst.l	d0		;is a0 = 0?
		beq.s	.start_prg	;yes, so .PRG
		
		move.l	a0,__base	;a0 is ptr to our basepage
		bra	.start_acc	;no, so .ACC...		

.start_wnx:
		move.w	#-1,__app	;__app=0xffff
		bra	.__START


.start_prg:	
		move.w	#1,__app	;__app=0x1
		move.l	4(a7),a0	;base page

		move.l	#stack+STKSIZE,a7
		
		move.l	$c(a0),d0	;text len
		add.l	$14(a0),d0	;data len
		add.l	$1c(a0),d0	;BSS len
		add.l	#$100,d0	;basepage
		
		move.l	d0,progsize
		
		move.l	d0,-(sp)
		move.l	a0,-(sp)
		clr.w	-(sp)
		move.w	#$4a,-(sp)
		trap	#1		;shrink memory
		lea	12(sp),sp

		bra.s	.__START

.start_acc:	
		move.w	#0,__app		;__app = 0
		move.l	#stack+STKSIZE,a7	;must have a stack!

.__START:	
		move.l	__base,a0
		move.l	44(a0),-(sp)
		pea	128(a0)
		jsr	__initargcv
		addq.l	#8,sp

			
		move.l	_environ,-(sp)
		move.l	__argv,-(sp)
		move.w	__argc,-(sp)
		
		jsr	_main

		addq.l	#2,sp

		cmp.w	#-1,__app
		beq	.wnx

		clr.w	-(a7)
		jsr	_exit

.wnx
		move.l	#0,-(sp)	;null parmblk.. we don't know...
		move.w	#39,-(sp)
		move.w	#-1,-(sp)
		trap	#5

		SECTION DATA
stksize		dc.l	STKSIZE

		SECTION BSS
__app		ds.w	1
__base		ds.l	1
_environ	ds.l	1
__argv		ds.l	1
__argc		ds.w	1
_seed		ds.l	1
_errno		ds.w	1
progsize	ds.l	1
	
stack		ds.b	STKSIZE+2
