/*
 * Task.c - a cheap sub-task example by cs
 *   Cheap =  shared data for communication rather than MsgPorts
 *   If using Aztec, #define AZTEC_C
 *
 *   Forgot to tell you - If you are using Lattice, you must use the -v
 *   flag on LC2 to disable Lattice's insertion of stack-checking code.
 *   That code will generate an alert if you have inline code which runs
 *   as a separate task, process, handler, etc.
 *
 *   If you are using Manx, compile long (-l ?) and link with the 32-bit
 *   library.  With a bit of work on the example, this might not be necessary.
 *
 */

#include <exec/types.h>
#include <exec/tasks.h>

extern VOID subTaskRtn();

struct Task *CreateTask(), *subTaskPtr = 0L;
char *subTaskName = "SubTask";

/* Data shared by main and subTaskRtn */
ULONG  GfxBase = 0L;
ULONG  Counter = 0L;
LONG   PrepareToDie;

/* If using Aztec, #define AZTEC_C 
 *
 * Note: Aztec C v3.4a has built in functions that do the following
 *  for you: geta4() and sava4().
 */

#ifdef AZTEC_C
#asm
		cseg
        public  _a4sav
_a4sav
		lea.l	_a4tmp,a0
        move.l  a4,(a0)
        rts

        public  _a4get
_a4get
        lea.l   _a4tmp,a0
        move.l  (a0),a4
        rts

		public  _a4tmp
	
_a4tmp   dc.l    0
        
#endasm
#endif


main()
   {
   int k;
   ULONG ct;

   if(!(GfxBase=OpenLibrary("graphics.library",0)))
      cleanexit("Can't open graphics.library");

   PrepareToDie = FALSE;

#ifdef AZTEC_C
   a4sav();
#endif

   subTaskPtr = CreateTask(subTaskName,0,subTaskRtn,2000);
   if (!subTaskPtr)  cleanexit("Can't create subTask");

   for (k=0; k<10; k++)
      {
      Delay(50);  /* main is a process and can call Delay() */
      ct = Counter;
      printf("Counter = %ld\n",ct);
      }

   cleanup();
   }

cleanexit(s)
char *s;
   {
   if(*s)  printf("%s\n",s);
   cleanup();
   exit(0);
   }

cleanup()
   {
   if(subTaskPtr)
      {
      PrepareToDie = TRUE;
      while(PrepareToDie);
      DeleteTask(subTaskPtr);
      }
   if(GfxBase)  CloseLibrary(GfxBase);
   }


/* subTaskRtn increments Counter every 1/60 second */
VOID subTaskRtn()
   {
#ifdef AZTEC_C
   a4get();
#endif

   while(!PrepareToDie)
      {
      WaitTOF();
      Counter++;
      }
   PrepareToDie = FALSE;  /* Signal ready to die */
   Wait(0L);              /* Wait while ax falls */
   }


