#include <exec/types.h>
#include <exec/nodes.h>
#include <exec/lists.h>
#include <exec/memory.h>
#include <utility/tagitem.h>
#include <powerup/ppclib/interface.h>
#include <powerup/ppclib/message.h>
#include <powerup/ppclib/tasks.h>
#include <powerup/gcclib/powerup_protos.h>

#define TEXT    "Text sent by PPC processor\n"
#define	DEBUG	0

struct StartupData
{
	void	*MsgPort;
	ULONG	MsgCount;
};

BPTR    MyFile;
void printf(char *String);

int	main(void)
{
struct TagItem		MyTags[10];
struct StartupData	*StartupData;
void			*ReplyPort;
void			*M68kPort;
void			*PPCMsg;
void			*M68kMsg;
void			*Body;
ULONG			result;
ULONG			MsgCount;
ULONG			i;

  StartupData	=(struct StartupData *) PPCGetTaskAttr(PPCTASKTAG_STARTUP_MSGDATA);
  MsgCount	=	StartupData->MsgCount;
#if DEBUG
  if (MyFile = PPCOpen("con:0/0/640/200/MessageDemo - PPC output/CLOSE", MODE_NEWFILE))
  {
#endif
    if (M68kPort=StartupData->MsgPort)
    {
#if DEBUG
      printf("Allocating memory for message body\n");
#endif
      if (Body = PPCAllocVec(sizeof(TEXT), MEMF_PUBLIC))
      {
#if DEBUG
        printf("Creating reply port\n");
#endif
        MyTags[0].ti_Tag = TAG_DONE;
        if (ReplyPort = PPCCreatePort(MyTags))
        {
#if DEBUG
          printf("Creating message\n");
#endif
          if (PPCMsg = PPCCreateMessage(ReplyPort, sizeof(TEXT)))
          {
#if DEBUG
            printf("Obtaining PPC port...");
#endif
            strcpy(Body, TEXT);

            for (i=0;i<MsgCount;i++)
            {
              PPCSendMessage(M68kPort,
                             PPCMsg,
                             Body,
                             sizeof(TEXT),
                             0x12345678);
              PPCWaitPort(ReplyPort);
              PPCGetMessage(ReplyPort);
            }

#if DEBUG
            printf("Deleting message port\n");
#endif
            while (PPCDeletePort(ReplyPort) == FALSE)
            {
/*
            PPCRawDoFmt("deleteport failed...\n",
                        NULL,
                        1,				// 0=Buffer,1=serial <> NOT supported yet
                        NULL);
*/
            }
          }
          else
          {
#if DEBUG
            printf("Could not create ppc msg\n");
#endif
          }

#if DEBUG
          printf("Deleting reply port\n");
#endif
          while (PPCDeletePort(ReplyPort) == FALSE);
        }
        else
        {
#if DEBUG
          printf("Could not create reply port\n");
#endif
        }

#if DEBUG
        printf("Freeing message body memory\n");
#endif
        PPCFreeVec(Body);
      }
      else
      {
#if DEBUG
        printf("Could not alloc mem for msg body\n");
#endif
      }

    }
    else
    {
#if DEBUG
      printf("Could not get a M68k msgport\n");
#endif
    }

#if DEBUG
    printf("Closing output\n");
    PPCClose(MyFile);
  }
#endif
}

void printf(char *String)
{
  PPCWrite(MyFile, String, strlen(String));
}

