/*****************************************************************************

                        LFRxDirect.c

                        LF Soft 1993

    This SoftWare is a PUBLIC DOMAIN so you can made what you want with it.
    Arexx routine come from CSH 5.19.

    As rxsend fonction of CSH is interne, you can't use it in backround.
    LFRxDirect does the same thing but it can be started as backround task.

    Syntax :
        LFRxDirect [-l] port cmd [cmd [ ... ]]

    with -l all arguments are send as one argument.

    History:

        13-12-1993  V1.0
        18-02-1994  v1.1 add -l option

 *****************************************************************************/
#include <LF.h>     // my own include file for LF.lib and handling DiceConfig stuffs
#include <string.h>
#include <proto/exec.h>
#include <proto/dos.h>
#include <clib/alib_protos.h>

static struct rexxmsg {
        struct Message cm_Node;
        LONG   RFU1;
        LONG   RFU2;
        LONG   rm_Action;
        LONG   rm_Result1;
        LONG   rm_Result2;
        char   *cm_Args[16];
        LONG   RFU7;
        LONG   RFU8;
        LONG   RFU9;
        LONG   RFU10;
        LONG   RFU11;
        LONG   RFU12;
} mymsg;

void send_rx(char *rx_prt,char *msg){
    struct MsgPort *prt,*reply;

    #ifdef DEBUG
        printf("prt: '%s'\ncom: '%s'\n",rx_prt,msg);
    #endif

    if(!(prt = FindPort(rx_prt))){
        LFatal("Can't find port !");
        exit(20);
    } else {
        mymsg.cm_Node.mn_Node.ln_Type = NT_MESSAGE;
        mymsg.cm_Node.mn_Length = sizeof(struct rexxmsg);
        mymsg.rm_Action = 0 ;
        if (!(reply = CreatePort(NULL, 0L))){
            LFatal("Unable to Create reply port");
            exit(20);
        } else {
            mymsg.cm_Node.mn_ReplyPort = reply;
            mymsg.cm_Args[0] = msg;
            PutMsg(prt, &mymsg.cm_Node);
            WaitPort(reply);

            DeletePort(reply);
        }
    }
}

void main(int ac, char **av){
    int i;

    OS2_0();    // OS2.0 is needed because of use of GetArgStr().

    if(ac<3){
        puts(" LFRxDirect v1.1 by LFSoft 1993-94\nSyntax :\n"
            "LFRxDirect [-l] port cmd [cmd [ ... ]]");
        exit(5);
    } else if(!strcmp(av[1],"-l")){
        char *x;

        if(ac<4){
            puts(" LFRxDirect v1.1 by LFSoft 1993-94\nSyntax :\n"
                "LFRxDirect [-l] port cmd [cmd [ ... ]]");
            exit(5);
        } else if(x=strdup(GetArgStr())){
            int i;
            while(*x && (*x==' ' || *x=='\t')) x++; // ' '
            while(*x && *x!=' ' && *x!='\t') x++; // jump -l
            while(*x && (*x==' ' || *x=='\t')) x++; // ' '
            while(*x && *x!=' ' && *x!='\t') x++; // jump the port name
            while(*x && (*x==' ' || *x=='\t')) x++; // ' '
            if(i=strlen(x)) if(x[i-1]=='\n') x[i-1]=0;

            send_rx(av[2],x);
        }
    } else
        for(i=2; i<ac; i++)
            send_rx(av[1],av[i]);
}
