;/*
FailAt 1
LC -M -v -cs -O -iINCLUDE:CompactH/ CLIanywhere.c
Blink CLIanywhere.o ND
Protect CLIanywhere +p
Quit
*/

#include <string.h>
#include <intuition/intuition.h>
#include <intuition/intuitionbase.h>
#include <libraries/dos.h>
#include <exec/memory.h>
#include <proto/intuition.h>
#include <proto/exec.h>
#include <proto/dos.h>

#define iswhite(c) ((c)==' '||(c)=='\t'||(c)=='\n')

int __asm CLIanywhere(register __a0 char *args, register __d0 int argl)
{
  ULONG ilock;
  struct Screen *s;
  USHORT flags;
  BPTR file, nullfh;
  char *cmd, *c;
  ULONG size = 0L;   /* this flags whether to FreeMem(cmd) or not */
  struct DosLibrary *DOSBase;
  struct IntuitionBase *IntuitionBase;

  DOSBase = (struct DosLibrary *)OpenLibrary("dos.library",33);
  if (!DOSBase) return(100);
  IntuitionBase = (struct IntuitionBase *)OpenLibrary("intuition.library",33);
  if (!IntuitionBase) return(100);

/*
**  process the command line args
*/

/* NULL-delimit args */
  c = (args + argl);
  *c = '\0';
/* trunc trailing newline */
  for(c--; (c > args) && iswhite(*c); c--) *c = '\0';
/* skip leading white space */
  while(iswhite(*args)) args++;

  if (*args)
    {
      cmd = args;
    }
  else
    {
      file = Open("s:CLIanywhere.cmd",MODE_OLDFILE);
      if (!file)
        {
          cmd = "c:NewShell \"NEWCON:0/11/640/50/ CLIanywhereShell \"";
        }
      else
        {
          Seek(file,0L,OFFSET_END);
          size = Seek(file,0L,OFFSET_CURRENT);
          size++;
          cmd = AllocMem(size,MEMF_PUBLIC);
          if (!cmd)
            {
              Close(file);
              return(100);
            }
          Seek(file,0L,OFFSET_BEGINNING);
          Read(file,(UBYTE *)cmd,size);
          Close(file);
          *(char *)(cmd + size - 1) = '\0';
        }
    }

  ilock = LockIBase(0L);
  s = IntuitionBase->FirstScreen;
  flags = s->Flags;
  s->Flags = ( (s->Flags & (~SCREENTYPE)) | WBENCHSCREEN);
  UnlockIBase(ilock);

  nullfh = Open("NIL:",MODE_NEWFILE);
  if (nullfh)
    {
      Execute(cmd,nullfh,nullfh);
      Close(nullfh);
    }

  ilock = LockIBase(0L);
  if (s == IntuitionBase->FirstScreen) s->Flags = flags;
  UnlockIBase(ilock);

  if (size > 0L) FreeMem(cmd,size);
  CloseLibrary((struct Library *)IntuitionBase);
  CloseLibrary((struct Library *)DOSBase);
  return(0);
}
