#include <exec/types.h>
#include <exec/nodes.h>
#include <exec/lists.h>
#include <exec/memory.h>
#include <powerup/ppclib/interface.h>
#include <powerup/ppclib/semaphore.h>
#include <powerup/gcclib/powerup_protos.h>

#define	SEMAPHORENAME	"TaskSemaphore"

char	Buffer[]="0:Task A is active\n";

ULONG main(void)
{
BPTR		MyFile;
ULONG		MySignal;
void		*Semaphore;
BOOL		MySemaphore;
BOOL		ObtainedByName;
struct TagItem	MyTags[10];
int		i;

  MySemaphore		=	FALSE;
  ObtainedByName	=	TRUE;
  if ((Semaphore=PPCObtainSemaphoreByName(SEMAPHORENAME))==NULL)
  {
    MyTags[0].ti_Tag	=	PPCSEMAPHORETAG_NAME;
    MyTags[0].ti_Data	=	(ULONG) SEMAPHORENAME;
    MyTags[1].ti_Tag	=	TAG_DONE;
    if ((Semaphore=PPCCreateSemaphore(MyTags))==NULL)
    {
      if ((Semaphore=PPCObtainSemaphoreByName(SEMAPHORENAME))==NULL)
      {
        /*
         * CreateSemaphore didn`t work and that wasn`t caused by a parallel TaskB
         * running
         */
        return(20);
      }
    }
    else
    {
      MySemaphore	=	TRUE;
      ObtainedByName	=	FALSE;
    }
  }

  if (MyFile=PPCOpen("con:0/0/640/200/TaskA/CLOSE",MODE_NEWFILE))
  {
    for (;;)
    {
      if (!ObtainedByName)
      {
        PPCObtainSemaphore(Semaphore);
      }
      for (i=0;i<10;i++)
      {
        Buffer[0]	=	'0'+i;
        PPCWrite(MyFile,
                 Buffer,
                 sizeof(Buffer));
      }
      PPCReleaseSemaphore(Semaphore);
      ObtainedByName	=	FALSE;
    }
    PPCClose(MyFile);
  }
  else
  {
    PPCRawDoFmt("Couldn`t open CLI Window\n",
                NULL,
                1,				/* 0=Buffer,1=serial <> NOT supported yet */
                NULL);
  }
  if (MySemaphore)
  {
    PPCDeleteSemaphore(Semaphore);
  }
  return(0);
}
