#include <libraries/dosextens.h>
#include <exec/ports.h>
#include <workbench/startup.h>
#include <workbench/workbench.h>
#include <stdio.h>

struct MsgPort *FindPort(), *CreatePort();
struct WBStartup *Launch(), *GetMsg();
struct Process *FindTask();

main(ac, av)
int ac;
char **av;
{
	struct MsgPort *rport;
	struct Process *me;
	struct CommandLineInterface *cli;
	struct WBStartup *startup;

	long stack;
	int pri;
	char *win;
	int wait;
	int got_arg;

	stack = 0;
	pri = 0;
	win = 0;
	wait = 0;

	if(ac < 2 || strcmp(av[1], "?") == 0) {
		fprintf(stderr,
"launch [stack nnnn] [window name] [priority PRI] [wait] program [arguments]\n"
			);
		exit((ac<2)?5:0);
	}
	got_arg = 1;
	while(got_arg == 1 && ac >= 3) {
		got_arg = 0;
		if(dictcmp(av[1], "window") == 0) {
			win = av[2];
			av += 2;
			ac -= 2;
			got_arg = 1;
		} else if(dictcmp(av[1], "stack") == 0) {
			stack = atol(av[2]);
			av += 2;
			ac -= 2;
			got_arg = 1;
		} else if(dictcmp(av[1], "priority") == 0) {
			pri = atoi(av[2]);
			av += 2;
			ac -= 2;
			got_arg = 1;
		} else if(dictcmp(av[1], "wait") == 0) {
			wait = 1;
			av ++;
			ac --;
			got_arg = 1;
		}
	}

	if(wait == 0) {
		if(!(rport = FindPort("Workbench.Cleanup"))) {
			fprintf(stderr, "Could not find Workbench.Cleanup port.\n");
			fprintf(stderr, "Are you sure you ran wbcleanup?\n");
			exit(20);
		}
	} else {
		if(!(rport = CreatePort(0, 0))) {
			printf("Can't create reply port.\n");
			exit(20);
		}
	}
	if(stack == 0) {
		me = FindTask(0);
		if(me->pr_CLI) {
			cli = (struct CommandLineInterface *)(me->pr_CLI<<2);
			stack = cli->cli_DefaultStack<<2; /* DefaultStack is in Longwords */
		} else
			stack = me->pr_StackSize;
	}
	if(!Launch(rport, av[1], &av[1], ac-1, pri, win, stack)) {
		fprintf(stderr, "Could not launch %s error %d\n", av[1], IoErr());
		exit(20);
	}
	if(wait != 0) {
		WaitPort(rport);
		startup = GetMsg(rport);
		FreeStartup(startup);
		DeletePort(rport);
	}
	exit(0);
}
