#include <libraries/dosextens.h>
#include <exec/ports.h>
#include "roguestar.h"
#include <stdio.h>

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

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

  long stack;
  int pri;
  char *win;
  int wait;
  int back;
  int got_arg;
  long in, out, err;

  stack = 0;
  pri = 0;
  win = 0;
  wait = 0;
  back = FALSE;

  if(ac < 2 || strcmp(av[1], "?") == 0) {
    fprintf(stderr, "rogue [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(stricmp(av[1], "window") == 0) {
       win = av[2];
       av += 2;
       ac -= 2;
       got_arg = 1;
    }
    else if(stricmp(av[1], "stack") == 0) {
      stack = atol(av[2]);
      av += 2;
      ac -= 2;
      got_arg = 1;
    }
    else if(stricmp(av[1], "priority") == 0) {
      pri = atoi(av[2]);
      av += 2;
      ac -= 2;
      got_arg = 1;
    }
    else if(stricmp(av[1], "back") == 0) {
      back=TRUE;
      av++;
      ac--;
      got_arg=1;
    }
    else if(stricmp(av[1], "wait") == 0) {
      wait = 1;
      av ++;
      ac --;
      got_arg = 1;
    }
  }

  if(wait == 0) {
    if(!(rport = FindPort("Rogue.Cleanup"))) {
      fprintf(stderr, "Could not find Rogue.Cleanup port.\n");
      fprintf(stderr, "Are you sure you ran roguecleanup?\n");
      exit(20);
    }
  }
  else {
    if(!(rport = CreatePort(0, 0))) {
      fprintf(stderr,"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(back==TRUE) {
    if((in=Open("NULL:",MODE_NEWFILE))==NULL) {
      fprintf(stderr,"Could not open NULL: device\n");
      exit(25);
    }
    out=err=in;
  }
  else {
    in=Input();
    out=Output();
    if((err=Open("*",MODE_OLDFILE))==NULL) {
      fprintf(stderr,"Can't open standard error\n");
      exit(25);
    }
  }
  if(!RogueLaunch(rport,av[1],&av[1],ac-1,NULL,pri,win,stack,in,out,err,0L)) {
     fprintf(stderr, "Could not launch %s error %d\n", av[1], IoErr());
     exit(20);
  }
  if(wait != 0) {
    WaitPort(rport);
    startup = GetMsg(rport);
    printf("Got %d\n",startup);
    RogueFreeStartup(startup);
    DeletePort(rport);
  }
  exit(0);
}
