include %c86.inc
	ttl	$MAIN, 1.01, 07-25-86 jwk

;	main entry point for all C programs under C86
;	similar changes must be made for other compilers

	dseg

	extv	_sysuglo, word
	extv	_sysvals, word
htop	equ	_sysvals[2]
	extv	_args, word

hem	db	0dh,0ah,'Not enough RAM to run!$'

dem	db	0dh,0ah,'DOS version 2.x or higher required!$'

	cseg

	extf	_main

	public	$main

$main	proc	near

	mov	ah,30h			;check DOS version
	int	21h
	mov	dx,ss			;save SS value
	cmp	al,2
	jnb	dok
	mov	ds,dx			;won't work with 1.x
	mov	dx,offset dem
	mov	ah,9
	int	21h
	int	20h			;so get right out

dok:	mov	ax,cs:2			;check RAM usage
	sub	ax,dx			;result is what's above code
	cmp	ax,1000h		;if <64K just use it
	jna	m01			;else cut back to 64K for DS/SS
; NOTE -- release unused RAM here to permit EXEC function later........
	mov	ax,1000h

m01:	mov	cx,4			;convert to byte count
	shl	ax,cl
	mov	si,80h			;look at PSP buffer
	mov	cl,byte ptr [cs:si]	;get character count
	add	cl,3
	and	cl,0feh			;force it to be even
	sub	ax,cx			;back up to leave space
	mov	sp,ax			;and set the SP
	mov	di,ax
	mov	ss:_args,ax		;save pointer to args
	assume	cs:code,ds:code,es:data,ss:data
	mov	es,dx
	cld
	rep movsb			;move to be above heap
	assume	cs:code,ds:data,es:data,ss:data
	mov	ds,dx			;set Data Segment after move
	mov	bp,cx			;zero BP now

	mov	di,_sysuglo		;start of heap per loader
	mov	cx,_sysuglo[2]		;size initialized by loader
	add	htop,di			;add to reserve
	add	htop,cx			;and increment by what's in use
	cmp	htop,sp
	jnb	herr
	xor	ax,ax
	rep	stosb			;clear the free space
	call	_main
	jmp	short	ex1
;
herr:	mov	ah,9
	mov	dx,ss			;be sure of DS
	mov	ds,dx
	mov	dx,offset hem
	int	21h
	mov	ax,00ffh		;255=heap error
	jmp	short	ex1
;
	public	_exit

_exit:	push	bp
	mov	bp,sp
	mov	ax,4[bp]
ex1:	mov	ah,4ch			; exit, set ret value
	int	21h

	public	$entry0
$entry0:
	pop	si
	xor	ax,ax
	jmp	short	entc
;

	public	$entry1
$entry1:
	pop	si
	cld
	db	2eh			;CS: prefix
	lodsb
	mov	ah,0
	jmp	short	entc
;

	public	$entry2
$entry2:
	pop	si
	cld
	db	2eh			;CS: prefix
	lodsw
entc:	push	bp
	mov	bp,sp
	sub	sp,ax
	cmp	sp,htop
	jna	herr
	jmp	si
;

	pend	$main

code	ends

	end
