
#include <exec/types.h>
#include <exec/alerts.h>
#include <exec/tasks.h>
#include <exec/libraries.h>
#include <libraries/dosextens.h>
#include <workbench/startup.h>
#include <functions.h>

#include <stdlib.h>

#include "istartup.h"

/*
crt0
  - handles wbstartup msg if run from WB
  - sets SysBase

void _main (ULONG arg_length, char *arg_string)
if ARG_STRING is zero and then ARG_LENGTH is the WBStartup message from WB
unless ARG_LENGTH is zero in which case the program was run without a CLI
but not from WB.
*/


/* _main.c */

static char **argv;

static void close_imain (void);

void
_main (LONG arg_length, char *arg_string)
{
  int argc;
  int status;

  DOSBase = OpenLibrary (DOSNAME, 0L);
  if (!DOSBase)
    {
      Alert (AG_OpenLib | AO_DOSLib, NULL);
      exit (100);
    }

  /* Write (Output (), "Yow!\n", 5); */

  if (!arg_string)
    {
      if (!__open_wb_stdio ((struct WBStartup *) arg_length))
	exit (100);
    }

  __open_stdio ();

  argv = NULL;
  if (arg_string)
    {
      struct Process *ThisProcess;
      struct CommandLineInterface *cli;
      UBYTE *cmd_string;
      size_t cmd_length;
      ThisProcess = (struct Process *) FindTask (NULL);
      cli = (struct CommandLineInterface *) BADDR (ThisProcess->pr_CLI);
      cmd_string = (UBYTE *) BADDR (cli->cli_CommandName);
      cmd_length = *cmd_string++;
      argc = __build_argv (&argv, (char *) cmd_string, cmd_length,
				  (char *) arg_string, arg_length);
      if (argc < 0)
	exit (100);
    }
  else
    {
      argc = 0;
      argv = (char **) arg_length;
    }

  __close_imain = close_imain;

  /* Call the main function. */
  status = main(argc, argv);

  exit(status);
}

static void
close_imain (void)
{
  if (argv)
    __free_argv (argv);
}
