#include <stdio.h>
#include <exec/types.h>
#include <utility/tagitem.h>
#include <powerup/ppclib/time.h>
#include <powerup/clib/ppc_protos.h>

extern void *PPCCreateTimerObject(struct TagItem*);
extern void PPCDeleteTimerObject(void*);
extern void PPCSetTimerObject(void*,ULONG,ULONG*);
extern void PPCGetTimerObject(void*,ULONG,ULONG*);


void printinfo(void *timer)
{
  ULONG r[2];

  PPCGetTimerObject(timer,PPCTIMERTAG_TICKSPERSEC,r);
  printf("Ticks per second................%08lx %08lx\n",r[0],r[1]);

  PPCGetTimerObject(timer,PPCTIMERTAG_START,r);
  printf("Start Time......................%08lx %08lx\n",r[0],r[1]);

  PPCGetTimerObject(timer,PPCTIMERTAG_STOP,r);
  printf("Stop Time.......................%08lx %08lx\n",r[0],r[1]);

  PPCGetTimerObject(timer,PPCTIMERTAG_CURRENTTICKS,r);
  printf("Current Ticks...................%08lx %08lx\n",r[0],r[1]);

  PPCGetTimerObject(timer,PPCTIMERTAG_DIFFMICRO,r);
  printf("Difference Start-Stop in µs.....%08lx %08lx\n",r[0],r[1]);
}


void startstop(void *timer,ULONG cmd)
{
  ULONG r[2];

  if (cmd==PPCTIMERTAG_START)
    printf("Starting timer\n");
  else if (cmd==PPCTIMERTAG_STOP)
    printf("Stopping timer\n");
  PPCSetTimerObject(timer,cmd,r);
}


void dosomething()
{
  int i;

  for (i=0; i<100; i++)
    printf("%4d\r",i);
  printf("\n");
}


main()
{
  void *timer;
  struct TagItem ti[4];
  ULONG sig;

  printf("\nCreating CPU Timer...\n");
  ti[0].ti_Tag = PPCTIMERTAG_CPU;
  ti[0].ti_Data = TRUE;
  ti[1].ti_Tag = TAG_END;
  if (timer = PPCCreateTimerObject(ti)) {
    printinfo(timer);
    startstop(timer,PPCTIMERTAG_START);
    printinfo(timer);
    dosomething();
    startstop(timer,PPCTIMERTAG_STOP);
    printinfo(timer);
    PPCDeleteTimerObject(timer);
  }

  printf("\n\nCreating 50Hz Notification Timer...\n");
  sig = (ULONG)PPCAllocSignal(-1);
  ti[0].ti_Tag = PPCTIMERTAG_50HZ;
  ti[0].ti_Data = 5*50;  /* 5s timer */
  ti[1].ti_Tag = PPCTIMERTAG_AUTOREMOVE;
  ti[1].ti_Data = TRUE;
  ti[2].ti_Tag = PPCTIMERTAG_SIGNALMASK;
  ti[2].ti_Data = 1L<<sig;
  ti[3].ti_Tag = TAG_END;
  if (timer = PPCCreateTimerObject(ti)) {
    printinfo(timer);
    startstop(timer,PPCTIMERTAG_START);
    printinfo(timer);
    PPCWait(1L<<sig);
    printf("** 5s notification arrived! **\n");
    startstop(timer,PPCTIMERTAG_STOP);
    printinfo(timer);
    PPCDeleteTimerObject(timer);
  }
  PPCFreeSignal((BYTE)sig);
}
