/*
 *  WAITFOR.C   A program to allow processes that use RUN EXECUTE to
 *              wait for their sub-processes to signal that they have
 *              completed their tasks (or are ready to start, etc).
 *
 *              Used in conjunction with SIGNAL.C
 *
 *              Copyright (c) 1989 by Davide P. Cervone, all rights reserved.
 */

#include <exec/types.h>
#include <exec/ports.h>
#include <libraries/dos.h>
#include <proto/exec.h>

#define ERROR_NONE           0      /* Normal exit status */
#define ERROR_CANCELLED     10      /* User pressed CTRL-C to cancel */
#define ERROR_BADPORTNAME   11      /* No port name on command line */
#define ERROR_PORTEXISTS    12      /* Port name already in use */
#define ERROR_CANTMAKEPORT  13      /* Error while trying to create the port */

#define SIGBREAKF_ANY\
   (SIGBREAKF_CTRL_C | SIGBREAKF_CTRL_D | SIGBREAKF_CTRL_E | SIGBREAKF_CTRL_F)


extern struct MsgPort *FindPort();
extern struct MsgPort *CreatePort();
extern long Wait();


static struct MsgPort *thePort;         /* pointer to the named port */


/*
 *  DoExit()
 *
 *  General purpose exit routine.  Deletes the named port, if one was
 *  created, then exits with the specified return code (EXECUTE will
 *  report the return code, but interactive users will get no message).
 *
 */

static void DoExit(status)
LONG status;
{
   if (thePort) DeletePort(thePort);
   _exit(status);
}


/*
 *  _main()
 *
 *  Replaces the standard Lattice _main routine (since no IO is performed
 *  we don't nee the usual overhead).  _main expects the command line 
 *  (as entered by the user, including with the program) to be on the
 *  stack as its PortName argument.
 *
 *
 *  First clear the DOS signals, in case any are set from before.
 *  Check that the port name exists, and skip over the command name
 *  in the command line, and any leading blanks.  The port name will
 *  be whatever remains on the command line, including blanks and
 *  special characters.
 *
 *  If the port name was specified, check to make sure the port does
 *  not already exist.  If it does, error exit, otherwise, create the
 *  named port, if possible.
 *
 *  Now, just wait for a signal fro mthat port (or for any DOS break
 *  signal).  If the user sent a BREAK (or pressed CTRL-C, D, E, or F)
 *  then error exit, otherwise, clean up the port and exit normally.
 */

void _main(PortName)
char *PortName;
{
   LONG theSignal;

   SetSignal(0L,SIGBREAKF_ANY);

   if (PortName == NULL) DoExit(ERROR_BADPORTNAME);
   
   while (*PortName != '\0' && *PortName != ' ') PortName++;
   if (*PortName == '\0' || *PortName == '\n') DoExit(ERROR_BADPORTNAME);
   while (*(++PortName) == ' ');

   if (FindPort(PortName)) DoExit(ERROR_PORTEXISTS);

   thePort = CreatePort(PortName,0);
   if (thePort == 0) DoExit(ERROR_CANTMAKEPORT);

   theSignal = Wait(SIGBREAKF_ANY | (1<<thePort->mp_SigBit));
   if (theSignal & SIGBREAKF_ANY)
      DoExit(ERROR_CANCELLED);
     else
      DoExit(ERROR_NONE);
}
