/*
 *	Startup.c - Copyright © 1991 by S.R. & P.C.
 *
 *	Created:	18 Feb 1991  11:36:37
 *	Modified:	30 Mar 1991  13:31:10
 *
 *	Make>> make
 */

#include "ParMBase.h"


extern struct ExecBase *SysBase;
extern struct Library  *DOSBase;

struct ParMBase *ParMBase;
struct ArpBase *ArpBase;
struct ReqLib  *ReqBase;
struct IconBase *IconBase;
struct IntuitionBase *IntuitionBase;
struct WBStartup *WBenchMsg;
int _argc;
char **_argv;


long DosWrite(BPTR file, char *buffer, long length);
#pragma amicall(DOSBase, 0x30, DosWrite(d1,d2,d3))

int main(int argc, char **argv);


void exit(int code)
{
	if (WBenchMsg)
	{
		Forbid();
		ReplyMsg((struct Message *)WBenchMsg);
	}
	CloseLibrary(ParMBase);
	Exit(code);
}


void _main(long alen, char *aptr)
{
	struct Library *DOSBase;
	struct Process *pp;

	pp = (struct Process *)SysBase->ThisTask;
	if (!pp->pr_CLI) {
		WaitPort(&pp->pr_MsgPort);
		WBenchMsg = (struct WBStartup *)GetMsg(&pp->pr_MsgPort);
	}
	if (!(ParMBase = (struct ParMBase *)OpenLibrary("parm.library",1L))) {
	    if (pp->pr_CLI && (DOSBase = OpenLibrary("dos.library",0L))) {
			DosWrite(pp->pr_COS, "You need parm.library V1+\n", 26L);
			CloseLibrary(DOSBase);
	    }
		if (WBenchMsg) {
			Forbid();
			ReplyMsg((struct Message *)WBenchMsg);
		}
		return;
	}
	ArpBase = ParMBase->ArpBase;
	ReqBase = ParMBase->ReqBase;
	IconBase = ParMBase->IconBase;
	IntuitionBase = (struct IntuitionBase *)ArpBase->IntuiBase;

	if (WBenchMsg) {
		CurrentDir(WBenchMsg->sm_ArgList->wa_Lock);
		_argv = (char **)WBenchMsg;
	}
	else {
		/*
		 *	WARNING: With that function, argv[] array will not start with the program
		 *	name but with it's first argument. If there's no args, argc will be zero.
		 */
		_argc = (int)GADS(aptr, alen, NULL, (char **)&_argv, "args/...");
		if (_argc < 0) {
			Puts(_argv[0]);
			exit(20);
		}
	}

	main(_argc, _argv);

	exit(0);
}


