/** message.c
  *
  *                     Copyright 1988, W.G.J. Langeveld
  *                           All Rights Reserved
  *                           Freely Distributable
  *
  *   Send a message to a particular host.
  *
  *   AUTHOR/DATE:  W.G.J. Langeveld, November 1987.
  *   ============
  *
  *	CURRENT VERSION:
  *
  *	This version has been converted to SAS C 6.5 format. It has been modified
  *	for modern definition sequences for ANSI compilation. This no longer works
  *	with OS versions prior to 2.04.
  *
  *   AUTHOR/DATE:  Joanne Dow, jdow@bix.com, June 1998.
  *   ============
  *
  **/

#include <functions.h>
#include "ralprotos.h"
#include <exec/types.h>
#include <exec/exec.h>
#include <proto/rexxsyslib.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

char *CAS( char * );
/**
 *
 *   Send the command strings a through g to the port "portname".
 *
**/
int SendPortMsg( char *portname, int n, char *args[], struct MsgPort *replyport )
{
	int result = 12, i;
	struct RexxMsg *msg = NULL;
	struct MsgPort *port = NULL, *rport = NULL;
	
	if (RexxSysBase == NULL)
		return(result);
	if (portname    == NULL)
		return(result);
	if (args        == NULL)
		return(result);
	
	if (replyport == NULL) 
	{
		rport = CreatePort(NULL, 0L);
		if (rport == NULL)
			goto cleanup;
		msg = CreateRexxMsg(rport, 0L, 0L);
	}
	else
	{
		msg = CreateRexxMsg(replyport, 0L, 0L);
	}
	
	if (msg == NULL)
		goto cleanup;
	
	for (i = 0; i < n; i++)
		msg->rm_Args[i] = (STRPTR) args[i];
	
	FillRexxMsg(msg, (long) n, 0L);
	msg->rm_Action = RXCOMM | (n - 1);
	msg->rm_Node.mn_Node.ln_Name = RXSDIR;
	
	Forbid();
	port = FindPort(portname);
	if (port)
		PutMsg(port,  (struct Message *) msg);
	Permit();
	
	result = 13;
	if (!port)
		goto cleanup;
	
	if (rport) 
	{
		WaitPort(rport);
		GetMsg(rport);
		if (result = (int) msg->rm_Result1)
			goto cleanup;
	}
	
	result = 0;
	
	cleanup:
	/*
	 *   Cleanup all allocated resources
	 */
	if (rport) 
	{
		DeletePort(rport);
		HandlePortReply(msg);
	}
	return(result);
}


char *rxf_sendp( long *err, int n, char *args[] )
{
	*err = 18;
	
	if ((n > 0) && args[0])
		*err = SendPortMsg(args[0], n - 1, &args[1], NULL);
	
	if (*err)
		return(NULL);
	return(CAS("1"));
}

char *whf_sendp( long *err, WORD n, char *args[] )
{
	char *msgargs[16];
	int i;
	
	msgargs[0] = args[1];
	msgargs[1] = args[0];
	
	for (i = 2; i < n; i++)
		msgargs[i] = args[i];
	
	return(rxf_sendp(err, n, msgargs));
}


HandlePortReply( struct RexxMsg *msg )
{
	if (!RexxSysBase)
		return;
	
	if (msg) 
	{
		ClearRexxMsg(msg, 16L);
		DeleteRexxMsg(msg);
	}
	return;
}
