
/*
 *  _MAIN.C
 *
 *  (c)Copyright 1990, Matthew Dillon, All Rights Reserved
 *
 *  Note that to use this _main we must be a process.  The programmer
 *  can overide our _main with his own if he wishes a task entry.
 *
 *  Note that we open '*' with modes 1005 so if the filesystem is our stderr
 *  we don't create a file called '*'.
 */

#include <exec/types.h>
#include <libraries/dos.h>
#include <libraries/dosextens.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <lib/bcpl.h>

typedef struct CommandLineInterface CLI;
typedef struct Process Process;

void *_WBMsg;

extern void *GetMsg();
extern void *FindTask();

void
_main(len, arg)
short len;
char *arg;
{
    Process *proc = (Process *)FindTask(NULL);

    if (proc->pr_Task.tc_Node.ln_Type == NT_PROCESS) {
	/*DOSBase = OpenLibrary("dos.library", 0);*/

	if (proc->pr_CIS) {
	    _IoStaticFD[0].fd_Fh    =	proc->pr_CIS;
	    _IoStaticFD[0].fd_Flags =	O_RDONLY | O_NOCLOSE | O_ISOPEN;
	}

	if (proc->pr_COS) {
	    _IoStaticFD[1].fd_Fh    =	proc->pr_COS;
	    _IoStaticFD[1].fd_Flags =	O_WRONLY | O_NOCLOSE | O_ISOPEN;
	}

	if (proc->pr_ConsoleTask) {
	    if (_IoStaticFD[2].fd_Fh = Open("*", 1005))
		_IoStaticFD[2].fd_Flags = O_WRONLY | O_ISOPEN;
	    else if (_IoStaticFD[2].fd_Fh = _IoStaticFD[1].fd_Fh)
		_IoStaticFD[2].fd_Flags = O_WRONLY | O_NOCLOSE | O_ISOPEN;
	}
    }

    _finitdesc(stdin,  0, __SIF_READ | __SIF_NOFREE);
    _finitdesc(stdout, 1, __SIF_WRITE| __SIF_NOFREE);
    _finitdesc(stderr, 2, __SIF_WRITE| __SIF_NOFREE);

    if (proc->pr_Task.tc_Node.ln_Type == NT_PROCESS) {
	CLI *cli;

	if (cli = BTOC(proc->pr_CLI, CLI)) {
	    char **av;
	    int ac;
	    unsigned char *copy = malloc(len+1);
	    unsigned char *cname = (unsigned char *)((long)cli->cli_CommandName << 2);

	    _slow_bcopy(arg, copy, len);
	    copy[len] = 0;
	    ac = _parseargs1(copy, len);
	    av = malloc((ac + 2) << 2);
	    _parseargs2(copy, av+1, ac);

	    ++ac;   /*	include arg0	*/

	    if (cname) {
		len = *cname;

		arg = malloc(len+1);
		_slow_bcopy(cname + 1, arg, len);
		arg[len] = 0;
	    }
	    av[0] = arg;
	    av[ac] = 0;
	    exit(main(ac, av));
	} else {
	    WaitPort(&proc->pr_MsgPort);
	    _WBMsg = GetMsg(&proc->pr_MsgPort);

	    exit(wbmain(_WBMsg));
	}
    }
    exit(-1);
}

