/*
*
*   This module is responsible for communicating with Rexx.
*   Specifically it opens a message port and tells rexx to execute
*   a program. Rexx should signal host of errors or death.
*
*/

#include "exec/types.h"
#include "exec/exec.h"
#include "rexx/storage.h"
#include "rexx/rxslib.h"
#include "rexx/errors.h"

/* system types */

extern void ClearMem(),AddPort(),FreePort(),InitPort(),RemPort(),Forbid();
extern void Permit();
extern LONG OpenLibrary();
extern struct RexxMsg *GetMsg();

/* My stuff */

struct RexxMsg *rmsg;
struct RexxTask *rxt;
struct RexxMsg *rxmsg, *port;

extern struct RexxLib *RexxSysBase;

#define PUBFAST MEMF_FAST+MEMF_PUBLIC+MEMF_CLEAR

void OpenRexxPort(string,port)
char *string;
struct MsgPort *port;
{

    ClearMem(port,(LONG)sizeof(struct MsgPort));
    InitPort(port,string);
    AddPort(port);

}

void DeleteRexxPort(port)
struct MsgPort *port;
{

    RemPort(port);
    FreePort(port);

}

long OpenLib(library,version)
char *library;
long version;
{
    long base;
    base = OpenLibrary(library,version);
    if( base == NULL ){
        printf("You need the %s library!\n",library);
        return(NULL);
    }
    return(base);
}

struct RexxMsg *PollRexxPort(port)
struct MsgPort *port;
{
    struct RexxMsg *rxport;

    rxport = GetMsg(port);
    if( rxport == NULL )
        return((struct RexxMsg *)NULL);
    return(rxport);

}

struct RexxMsg *WaitRexxPort(port)
struct MsgPort *port;
{

    Wait(1<<port->mp_SigBit);
    return(PollRexxPort(port));

}

/* Used by main routine... saves me some typing there. */
long CleanupRexx(rexport)
struct RexxMsg *rexport;
{
    struct RexxMsg *rmg;

    rmg = WaitRexxPort(rexport);
    ClearRexxMsg(rxmsg,1L);  /* this releases the string in the msg */
    DeleteRexxMsg(rxmsg);
}

long StartRexxProg(rexport)
struct RexxMsg *rexport;
{
    struct RexxMsg *rmg;

    rxmsg = CreateRexxMsg(rexport,"flex","flport");

    Forbid();
    port = (struct RexxMsg *)FindPort("REXX");
    if(port == NULL){
        Permit();
        DeleteRexxMsg(rxmsg);
        return(FALSE);
    }

    rxmsg->rm_Args[0] = "fl";
    rxmsg->rm_Action = RXCOMM;

    FillRexxMsg(rxmsg,1L,0L); /* store the message */

    PutMsg(port,rxmsg); /* email in it's truest form */
    Permit();
    return(TRUE);
}
