#include <exec/types.h>
#include <exec/ports.h>
#include <exec/memory.h>
#include <dos/dos.h>
#include <clib/exec_protos.h>
#include <clib/alib_protos.h>
#include <stdio.h>
#include <stdlib.h>
#include "MultiChat.h"
#include <doorheader.h>
#include "ChatMsg.h"

int SafePutToPort(struct Message *, STRPTR);

UWORD SendMsg(char Text)
{
	struct ChatMsgStruct *ChatMsg;
	struct MsgPort *ChatMsgReplyPort;

	extern char *PortNames[];
	extern char *ReplyPortNames[];
	char		Buf[100];
	char		YourNode_char[200];
	
	UWORD	NodeNr;
	UWORD	Status = TRUE;
	UWORD	YourNode;


	getuserstring(YourNode_char, BB_NODEID);
	YourNode = atoi(YourNode_char);

	for (NodeNr = 0; NodeNr <= 32; NodeNr++)
	{
		if (YourNode != NodeNr)
		{
			if (ChatMsg = (struct ChatMsgStruct *)AllocMem(sizeof(struct ChatMsgStruct), MEMF_PUBLIC | MEMF_CLEAR))
			{
				if (ChatMsgReplyPort = CreatePort(ReplyPortNames[NodeNr], 0))
				{
					ChatMsg->chat_Msg.mn_Node.ln_Type = NT_MESSAGE;
					ChatMsg->chat_Msg.mn_Length = sizeof(struct ChatMsgStruct);
					ChatMsg->chat_Msg.mn_ReplyPort = ChatMsgReplyPort;
					ChatMsg->Text = Text;
				 
					if (SafePutToPort((struct Message *)ChatMsg, PortNames[NodeNr]))
					{
						WaitPort(ChatMsgReplyPort);
						ChatMsg = (struct ChatMsgStruct *)GetMsg(ChatMsgReplyPort);
					}
					DeletePort(ChatMsgReplyPort);
				}
				FreeMem(ChatMsg, sizeof(struct ChatMsgStruct));
			}
			else
			{
				sprintf(Buf, "Couldn't allocate memory for message structure.\r\n");
				sendmessage(Buf, 0);
			}
		}
	}
	return(Status);
}

int SafePutToPort( struct Message *message, STRPTR portname)
{
	struct MsgPort *ChatPort;

	Forbid();
	ChatPort = FindPort(portname);
	if (ChatPort) PutMsg(ChatPort, message);
	Permit();
	return(ChatPort ? TRUE : FALSE);
}
