#include <devices/timer.h>
#include <dos/dos.h>
#include <exec/types.h>
#include <mine/toolkit.h>
#include <proto/dos.h>
#include <proto/exec.h>
#include <proto/timer.h>

struct MyArgs 
{ 
  long *loop;
};

static const char ver[] = "$VER: Timec 1.0 ("__DATE__")";
static const char template[]= "LOOP/N/K";

long main(void)
{
struct timeval      c1,c2,
                    cmax      = { 0x7fffffff,0 };
struct Library     *TimerBase = 0;
struct MsgPort     *timport   = 0;
struct DosLibrary  *DOSBase   = 0;
struct timerequest *timio     = 0;
struct RDArgs      *rdargs    = 0;
struct MyArgs       args      = { 0 };
byte                oldpri;
long                error     = 0;
ulong               loop,i,per,min,now,nul;

  oldpri = SetTaskPri(FindTask(0),-126);
  if (DOSBase = OpenLibrary("dos.library",37)) {
    if (rdargs=ReadArgs(template,(LONG *)&args,NULL)) {
      loop = (args.loop) ? (*args.loop) : 500000;
      if (timport = CreateMsgPort()) {
        if (timio = (struct timerequest *)CreateIORequest(timport,sizeof(struct timerequest))) {
          if (OpenDevice(TIMERNAME,UNIT_VBLANK,(struct IORequest *)timio,0) == 0) {
            TimerBase = timio->io_Device;
            PutStr("Timec V1.0, simple cpu available calc.\n");
  
            while ( (SetSignal(0L,SIGBREAKF_CTRL_C) & SIGBREAKF_CTRL_C) != SIGBREAKF_CTRL_C )
            {
              GetSysTime(&c1);
              for (i=0; i < loop;i++)
              {
                nul++; /* uh, without this SAS/C would optimize loop away :) */
              }
              GetSysTime(&c2);
              SubTime(&c2,&c1);
              if (CmpTime(&cmax,&c2) == -1) { /* if new record time */
                cmax.tv_secs  = c2.tv_secs;
                cmax.tv_micro = c2.tv_micro;
              }
              min = cmax.tv_secs * 1000000 + cmax.tv_micro;
              now =   c2.tv_secs * 1000000 +   c2.tv_micro;
              per = (min) ? now * 100 / min : 0;
              Printf("Time: %ld.%06ld (%3ld)   \r",c2.tv_secs,c2.tv_micro,per-100);
            }
  
            PutStr("\n");
          }
        }
      }
    } else {
      error = IoErr();
    }
  }
  if (DOSBase) {
    if (error    ) PrintFault(error,"Timec");
    if (rdargs   ) FreeArgs(rdargs);
    if (DOSBase  ) CloseLibrary(DOSBase);
  }
  if (TimerBase) CloseDevice((struct IORequest *)timio);
  if (timio    ) DeleteIORequest((struct IORequest *)timio);
  if (timport  ) DeleteMsgPort(timport);
  SetTaskPri(FindTask(0),oldpri);
  return(error);
}
