;	This is a Public Domain Assembly language startup file
;	Based on code described in the Amiga ROM Kernel Manuals
;
;	This code sets up the necessary items for programs to
;	run from either CLI or Workbench.
;
;	Written By: Douglas J Leavitt
;	Release:    1.1

;	Internal Macros

XLIB	macro
	xref	_LVO\1
	endm

LINKLIB	macro
	jsr	_LVO\1(a6)
	endm

;	Externally defined global variables

	xref	_AbsExecBase, _Input, _Output
	xref	_main

;	Internal global variables

	xdef	_SysBase, _errno
	xdef	_exit
	XLIB	FindTask

;	Internal Defines
	TC_SIZE = 92
	MP_SIZE = 34
	pr_CLI = TC_SIZE+MP_SIZE+46
	cli_CmdName = 4

;	Entry Point is called startup for Backwards compatibility
;	reasons.

	text
startup:
	move.l	sp,startSP		; Save passed registers
	move.l	d0,CLlen
	move.l	a0,CLbuf

	move.l	_AbsExecBase,a6		; Get the only known ref point
	move.l	a6,_SysBase

	sub.l	a1,a1
	LINKLIB	FindTask
	move.l	d0,a4

	tst.l	pr_CLI(a4)
	jeq	fromWB

;;;;;;;;;;
;
;	Started from CLI
;
;;;;;;;;;;

fromCLI:

;	Find command line
	move.l	pr_CLI(a4),a0
	add.l	a0,a0			; Get BCPL pointer ???
	add.l	a0,a0
	move.l	cli_CmdName(a0),a0
	add.l	a0,a0			; Get BCPL pointer ???
	add.l	a0,a0

;	Fetch and Copy Buffer
	movem.l	d2|a2|a3,-(sp)
	lea	ArgvBuf,a2		; Char array for command line
	lea	ArgvArray,a3		; Actual argv array
	moveq	#1,d2

;	Setup Argv[0] (command name)
	moveq	#0,d0
	move.b	(a0)+,d0		; Get command name size
	move.l	a2,(a3)+		; Get pointer to command name
	bra.s	av1
av2:
	move.b	(a0)+,(a2)+		; Copy name
av1:
	dbf	d0,av2
	clr.b	(a2)+

;	Get the remaining parameters
	move.l	CLlen,d0
	move.l	CLbuf,a0
ws1:
	move.b	(a0)+,d1		; Get next char
	subq.l	#1,d0
	jle	pExit
	cmp.b	#0x20,d0		; Skip Blanks
	ble.s	ws1
	addq.l	#1,d2			; Incr argc
	move.l	a2,(a3)+		; Save next argv
	bra.s	sv1
sv2:
	move.b	(a0)+,d1		; Get next char
	subq.l	#1,d0
	ble.s	pExit
	cmp.b	#0x20,d0		; End of Arg?
	ble.s	eParm
sv1:
	move.b	d1,(a2)+		; Save a char
	bra.s	sv2
eParm:
	clr.b	(a2)+			; Terminate string
	bra.s	ws1
pExit:
	clr.b	(a2)+
	clr.l	(a3)+
	move.l	d2,d0
	movem.l	(sp)+,d2|a2|a3

;	Prepare stack to Go
	pea	ArgvArray
	move.l	d0,-(sp)

;	GO!!!!

go:	jsr	_main
	clr.l	d0
	bra.s	exit2			; Falling off the end is a exit(0)
_exit:
	move.l	4(sp),d0		; Get the exit argument
exit2:
	move.l	startSP,sp
	rts

;;;;;;;;;;
;
;	Started From WorkBench
;
;;;;;;;;;;

fromWB:

;	When Starting from WB set argc, and argv to be 0
;	This is like the lattice compiler (a way to detect where
;	you came from.

	move.l	ArgvArray,a0
	clr.l	(a0)
	move.l	a0,-(sp)
	clr.l	-(sp)
	jra	go

;;;;;;;;;;
;
;	DATA section
;
;;;;;;;;;;

	data

_SysBase:
	dc.l	0

_errno:
	dc.l	0

startSP:
	dc.l	0
CLlen:
	dc.l	0
CLbuf:
	dc.l	0

ArgvArray:
	ds.l	64
ArgvBuf:
	ds.b	512

DOSName:
	dc.b	'd', 'o', 's', '.'
	dc.b	'l', 'i', 'b', 'r'
	dc.b	'a', 'r', 'y'
	dc.b	0
