#pragma amiga-align
#include <exec/tasks.h>
#include <dos/dos.h>
#include <utility/tagitem.h>
#include <proto/exec.h>
#include <proto/dos.h>

#pragma default-align
#define __SASC
#include <powerup/ppclib/interface.h>
#include <powerup/ppclib/message.h>
#include <powerup/ppclib/tasks.h>
#include <powerup/gcclib/powerup_protos.h>
#undef __SASC

#include <stdio.h>
#include <string.h>

#include "portlists.h"

static BPTR out;



static void myprint(char *s)
{
  PPCWrite(out,s,strlen(s));
}


static void waitreply(void *p,void *msg)
{
  void *m;

  myprint("  Waiting for reply...\n");
  for (;;) {
    if (m = PPCGetMessage(p)) {
      if (m == msg) {
        myprint("  Got it!\n");
        break;
      }
      else
        myprint("  Got reply of an unknown message, continue with waiting...\n");
    }
    PPCWaitPort(p);
  }
}


int	main(void)
{
  void *message;
  void *myPort = (void *)PPCGetTaskAttr(PPCTASKTAG_MSGPORT);
  struct StartupData *startup = (struct StartupData *)
                                 PPCGetTaskAttr(PPCTASKTAG_STARTUP_MSGDATA);

  if (myPort!=NULL && startup!=NULL) {
    if (out = PPCOpen("CON:0/0/640/200/PortLists Demo/CLOSE", MODE_NEWFILE)) {
      myprint("PPC Task started!\n\n");

      myprint("Creating PPC Message\n");
      if (message = PPCCreateMessage(myPort,0)) {

        myprint("Sending message to port 0\n");
        PPCSendMessage(startup->port[0],message,0,0,1);
        waitreply(myPort,message);
        Delay(50);
        myprint("Sending message to port 1\n");
        PPCSendMessage(startup->port[1],message,0,0,2);
        waitreply(myPort,message);
        Delay(50);
        myprint("Signaling M68k task\n");
        Signal(startup->sigtask,startup->sigmask);
        Delay(50);
        myprint("Sending message to port 2\n");
        PPCSendMessage(startup->port[2],message,0,0,3);
        waitreply(myPort,message);

        Delay(50);
        myprint("Deleting message\n");
        PPCDeleteMessage(message);
      }
      else
        myprint("Couldn't create PPC Message!\n");

      myprint("\nClosing window...\n");
      Delay(100);
      PPCClose(out);
    }
  }
  return 0;
}
