/*
   script.library
   host example
*/

#include <stdio.h>
#include <stdlib.h>

#include <dos/dos.h>
#include <rexx/rxslib.h>
#include <rexx/storage.h>

#include <proto/dos.h>
#include <proto/exec.h>
#include <proto/rexxsyslib.h>

#if defined (__SASC)
#include "/script.h"
#include "/script_pragmas.h"
#elif defined (__GNUC__)
#include "../script_inline.h"
#endif

#include "example.h"

#if defined (__GNUC__)
#define RXSLIB struct RxsLib
#elif defined (__SASC)
#define RXSLIB struct Library
#endif

RXSLIB *RexxSysBase = NULL;
struct Library *ScriptBase = NULL;
struct MsgPort *MyPort = NULL;

char *port_name = PORT_NAME,
     *func_name = FUNC_NAME,
     *variable_name  = VAR_NAME,
     *variable_value,
     *return_value = RET_VALUE;

void
Cleanup (void)
{
  struct Message *msg;

  if (MyPort)
  {
    Forbid ();
    RemPort (MyPort);
    Permit ();
    while (msg = GetMsg (MyPort))
      ReplyMsg (msg);
    DeleteMsgPort (MyPort);
  }
  if (RexxSysBase)
  {
    CloseLibrary ((struct Library *) RexxSysBase);
  }
  if (ScriptBase)
  {
    CloseLibrary (ScriptBase);
  }
}

void
Mainloop (void)
{
  struct RexxMsg *msg;
  ULONG mask;

  mask = 1 << MyPort -> mp_SigBit;

  for (;;)
  {
    if (Wait (SIGBREAKF_CTRL_C | mask) & SIGBREAKF_CTRL_C)
      break;

    while (msg = (struct RexxMsg *) GetMsg (MyPort))
    {
      Script_GetRexxVar (msg, variable_name, &variable_value);
      PutStr (variable_name);
      PutStr (" = ");
      if (variable_value)
        PutStr (variable_value);
      else
        PutStr ("<null>");
      PutStr ("\n");

      Script_SetRexxVar (msg, variable_name, return_value);
      msg -> rm_Result1 = 0;

      ReplyMsg ((struct Message *) msg);
    }
  }
}

int
main (int argc, char *argv[])
{
  atexit (Cleanup);

  if (argc >= 2)
    port_name = argv[1];
  if (argc >= 3)
    func_name = argv[2];
  if (argc >= 4)
    variable_name = argv[3];
  if (argc >= 5)
    return_value = argv[4];

  if (!(ScriptBase = OpenLibrary ("script.library", 0)))
  {
    PutStr ("Can't open script.library.\n");
    return 20;
  }
  if (!(RexxSysBase = (RXSLIB *) OpenLibrary ("rexxsyslib.library", 36)))
  {
    PutStr ("Can't open rexxsys.library.\n");
    return 20;
  }
  if (!(MyPort = CreateMsgPort ()))
  {
    PutStr ("Can't create port.\n");
    exit (20);
  }
  MyPort -> mp_Node.ln_Name = port_name;
  MyPort -> mp_Node.ln_Pri  = 0;

  Forbid ();
  if (FindPort (port_name))
  {
    Permit ();
    PutStr ("Port already in use.\n");
    DeleteMsgPort (MyPort);
    MyPort = NULL;
    exit (20);    
  }
  AddPort (MyPort);
  Permit ();

  Mainloop ();
  PutStr ("Done\n");
  exit (0);
}
