/*
 *  LISTEN.C
 *
 *  LISTEN port
 *
 *  receives data from port and prints results.
 */

#include "defs.h"
#include <exec/types.h>
#include <exec/io.h>
#include <exec/ports.h>
#include <libraries/dos.h>
#include <devices/parnet.h>

typedef struct IORequest IOR;

IOParReq iob[2];

extern PORT *CreatePort();

int
brk(void)
{
    return(0);
}

void
main(ac, av)
int ac;
char *av[];
{
    PORT *port = CreatePort(NULL, 0);
    char buf1[16];
    char buf2[16];

    onbreak(brk);
    iob[0].io_Message.mn_ReplyPort = port;
    iob[0].io_Port = atoi(av[1]);
    iob[0].io_Flags= PRO_DGRAM;

    if (OpenDevice("parnet.device", 0, (IOR *)&iob[0], 0)) {
	printf("Unable to open parnet.device, error %d %d\n", iob[0].io_Error, iob[0].io_Actual);
	exit(1);
    }
    printf("Device $%08lx Unit $%08lx\n", iob[0].io_Device, iob[0].io_Unit);

    iob[0].io_Command = CMD_READ;
    iob[0].io_Data    = (APTR)buf1;
    iob[0].io_Length  = sizeof(buf1);

    iob[1] = iob[0];     /* this is *dirty* ; the complete structure should
                            be copied */
    iob[1].io_Data    = (APTR)buf2;

    SendIO((IOR *)&iob[0]);
    SendIO((IOR *)&iob[1]);

    for (;;) {
	long mask;
	IOParReq *io;

	mask = Wait(SIGBREAKF_CTRL_E | (1 << port->mp_SigBit));

	if (mask & SIGBREAKF_CTRL_E)
	    break;

	while (io = (IOParReq *)GetMsg(port)) {
	    if (io->io_Actual < 0)
		printf("READ %d\n", io->io_Actual);
	    else {
		((char *)io->io_Data)[io->io_Actual] = 0;
		printf("READ %d %s\n", io->io_Actual, io->io_Data);
	    }
	    SendIO((IOR *)io);
	}
    }
    printf("Aborting...\n");
    AbortIO((IOR *)&iob[0]);
    AbortIO((IOR *)&iob[1]);
    WaitIO((IOR *)&iob[0]);
    WaitIO((IOR *)&iob[1]);
    printf("Closing...\n");
    CloseDevice((IOR *)&iob[0]);
    DeletePort(port);
}

