/* $VER: pro_sysdep.c V0.2 (31.08.98)
 *
 * Portable profiler for vbcc. AMIGA OS/68k specific part.
 * Copyright (c) 1998  Frank Wille
 *
 * The vbcc profiler is split into a system independant (profiler)
 * and in a system specific (prof_sysdep) part.
 *
 * v0.2  (31.08.98) phx
 *       Make sure profiler doesn't crash under Kickstart 1.x.
 * v0.1  (28.08.98) phx
 *       File created.
 */

#include <exec/types.h>
#include <exec/execbase.h>
#include <devices/timer.h>
#include <proto/exec.h>
#include <stdio.h>

void _GetSysTime(__reg("a0") struct timeval *,
                 __reg("a6") void *) = "\tjsr\t-66(a6)";

static void *timerbase = NULL;
static struct IORequest *timerio;
static struct timeval start;


int _prof_inittimer()
{
  struct MsgPort *timerport;

  if (SysBase->LibNode.lib_Version < 36)
    return (0);
  if (timerport = CreateMsgPort()) {
    if (timerio = CreateIORequest(timerport,sizeof(struct timerequest))) {
      if (OpenDevice(TIMERNAME,UNIT_MICROHZ,timerio,0) == 0) {
        timerbase = timerio->io_Device;
      }
      else {
        DeleteIORequest(timerio);
        DeleteMsgPort(timerport);
      }
    }
    else
      DeleteMsgPort(timerport);
  }
  if (!timerbase) {
    fprintf(stderr,"_prof_inittimer: Can't get timer.device for profiling!\n");
    return (0);
  }
  _GetSysTime(&start,timerbase);
  return (1);
}


void _prof_timerexit()
{
  if (timerbase) {
    if (!CheckIO(timerio)) {
      AbortIO(timerio);
      WaitIO(timerio);
    }
    CloseDevice(timerio);
    DeleteMsgPort(timerio->io_Message.mn_ReplyPort);
    DeleteIORequest(timerio);
  }
}


unsigned long _prof_time()
{
  static struct timeval tv;

  _GetSysTime(&tv,timerbase);
  return (((long)tv.tv_secs-(long)start.tv_secs)*1000000 +
          ((long)tv.tv_micro-(long)start.tv_micro));
}
