/********************************************************************
 ** PARALLEL PORT STUFF
 **
 ** (c) Spak, Darrell Tam, c9107253@ee.newcastle.edu.au (1994)
 ** phone (Australia) 049-829-710
 **                    49-829-710
 ** (c) SST 1994
 **
 ** LITTLE TEST CLIENT (A "SERVER") FOR RECEIVING
 **
 ** TABS to 4
 ********************************************************************/

#include "/snd/everything.h"
#include <st/st_proto.h>
#include "parstuff.h"


#define OUR_SERVER_PORT 11
struct	IntuitionBase *IntuitionBase = NULL;
struct	GfxBase *GfxBase = NULL;


long out;
main()
{
struct MsgPort *port = NULL, *theport = NULL, *repport = NULL;
	out = Output();

	if(!(IntuitionBase = (struct IntuitionBase *)OpenLibrary("intuition.library", 0))
	|| !(GfxBase = (struct GfxBase *)OpenLibrary("graphics.library", 0)) )
			goto nomore;

	if(!(port = CreatePort(0,0)) ||			/* service port */
	   !(repport = CreatePort(0,0))) {		/* reply port */
		fpf(out, "No ports\n");
		goto nomore;
	}

	if(!(theport = FindPort("ParRegister")) ) {
		fpf(out, "Couldn't find par port packet thingy\n");
		goto nomore;
	}

/** REGISTER WITH THE PARALLEL THING */
{
struct RegisterMsg rm;
	INIT_REGISTERMSG(&rm, port, RM_ADD_SERVER, OUR_SERVER_PORT, port, NULL); 
	PutMsg(theport, &rm); WaitPort(port); GetMsg(port);
	if(!rm.smsg.result) {
		fpf(out, "Couldn't add this as another port sucker\n");
		goto nomore;
	}
	fpf(out, "Registered ok as port server (%ld)\n", OUR_SERVER_PORT);
}


/** SIT IN A LOOP ON OUR PORT OR DIE ON CTRL C */
{
long mask, waitmask, pmask, rmask;
struct PktMsgRecv *pmr;
char *ret = "hello there how are you feeling today?..................";

	waitmask =	(pmask = 1<<port->mp_SigBit) |
				(rmask = 1<<repport->mp_SigBit) |
				SIGBREAKF_CTRL_C;

	while(! ((mask = Wait(waitmask)) & SIGBREAKF_CTRL_C) ) {

		if(mask & pmask) {
			while(pmr = (struct PktMsgRecv *)GetMsg(port)) {
				fpf(out,"Got a packet from (%lc) : %s\n"
						"pmr=%lx\n",
						pmr->pm.dest, pmr->pm.send_body, pmr);

				INIT_MSG(&pmr->pm.smsg.msg,  repport, sizeof(*pmr));
				INTERNAL_PREP_PKTMSG_DMA(&pmr->pm,
										EMEM_RETURNMSG,
										SERV_RETURN,
										ret, 40);
				PUT_STDMSG(&pmr->pm.smsg, pmr->dmaport, TYPE_INTERNAL_SEND);
			}
		}

		if(mask & rmask) {
			while(pmr = (struct PktMsgRecv *)GetMsg(repport)) {
				fpf(out, "Done: %lx\n", pmr);
				FREE_PKTMSGRECV(pmr);
			}
		}
	}
}
	fpf(out,"Quitting... (telling server) ");

/** REMOVE US AS A SERVER FROM THE THING */
{
struct RegisterMsg rm;
struct Message *maj;

	INIT_REGISTERMSG(&rm, port, RM_REMOVE_SERVER, OUR_SERVER_PORT, NULL, NULL); 
	for(PutMsg(theport, &rm); (WaitPort(port), (maj = GetMsg(port)) != &rm);)
					ReplyMsg(maj); /* important to return all messages but ours */
}

	fpf(out,"Done\n");

nomore:
	if(port) DeletePort(port);
	if(repport) DeletePort(repport);
	if(GfxBase) CloseLibrary((struct Library *)GfxBase);
	if(IntuitionBase) CloseLibrary((struct Library *)IntuitionBase);
}

