/* rxsend.c */

#include <stdio.h>
#include <string.h>
#include <exec/types.h>
#include <exec/ports.h>
#include <proto/exec.h>

#define check(F,M) { if (!(F)) { puts(M); clall(20); } }

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;

struct MsgPort *port, *reply;

puts(s)
char *s;
{
Write(Output(),s,strlen(s));
Write(Output(),"\n",1);
}

void clall(n)
{
if (reply) DeletePort(reply);
Exit(20);
}

void sendtoport(msg)
char *msg;
{
mymsg.cm_Node.mn_Node.ln_Type = NT_MESSAGE;
mymsg.cm_Node.mn_Length = sizeof(struct rexxmsg);
mymsg.rm_Action = 0;
mymsg.cm_Node.mn_ReplyPort = reply;
mymsg.cm_Args[0] = msg;
mymsg.rm_Result2 = 0;	/* clear out the last result. */
PutMsg(port, &(mymsg.cm_Node));
WaitPort(reply);
GetMsg(reply);
}

void main(argc, argv)
char *argv[];
{
register unsigned short i;

check(reply=CreatePort(0,0), "Can't create reply port");
for (i=1; i<argc; i++) execute(argv[i]);
}

execute(s)
char *s;
{
FILE *fp;
char buf[80];
static int verbose;
int n;

if (verbose) puts(s);
if (s[0] != '-') {
	check(port, "No port specified\n");
	sendtoport(s);
	}
else if (s[0]=='#')
	; /* comment: do nothing */
else switch(tolower(s[1])) {
	case 'p':	/* set destination message port */
		check(port=FindPort(s+2), "MsgPort not found");
		break;
	case 'f':	/* get options from a file */
		check( fp=fopen(s+2, "r"), "File not found");
		while (fgets(buf, 80, fp)) {
			n=strlen(buf);
			if (n && buf[n-1]=='\n') buf[n-1]=0;
			execute(buf);
			}
		fclose(fp);
		break;
	case 'v':	/* toggle verbose mode */
		verbose = !verbose ;
		break;
	default:
		puts("Unrecognized option");
		break;
	}
}
