
#include <exec/types.h>
#include <exec/execbase.h>
#include <exec/nodes.h>
#include <exec/resident.h>
#include <exec/errors.h>
#include <exec/semaphores.h>
#include <libraries/expansionbase.h>
#include <libraries/configvars.h>
#include <devices/trackdisk.h>

/*
 * Set SysBase to a local variable, that loads directly from 4 when it
 * has to be reloaded
 */
#define PRIVATE
#define BASE_EXT_DECL
#define BASE_NAME (*(void **)4)
#include <inline/exec.h>
#undef PRIVATE

#ifdef DEBUG

#include "device.h"

extern struct MsgPort *CreatePort();
extern void DeletePort(struct MsgPort *mp);

static inline int strcmp(char *s, char *d)
{
  while (*s && *s == *d) ++s, ++d;
  return *s-*d;
}

/* no more evil enforcer hits:-)) */
struct MsgPort *
myFindPort(char *name)
{
  struct MsgPort *mp, *np;
  struct ExecBase *SysBase = *(struct ExecBase **)4;

  Forbid();
  for (mp = (struct MsgPort *)SysBase->PortList.lh_Head;
       np = (struct MsgPort *)mp->mp_Node.ln_Succ;
       mp=np)
    if (mp->mp_Node.ln_Name && !strcmp(mp->mp_Node.ln_Name, name)) break;
  Permit();
  
  return np ? mp : 0;
}

void
dprintf(fmt, a0,a1,a2,a3,a4,a5,a6,a7)
  char *fmt;
  int a0,a1,a2,a3,a4,a5,a6,a7;
{
  struct MsgPort *mp, *op;
  struct Message ms[2];
#if 0
  static struct SignalSemaphore ss;
  static int sem_ok = 0;
#endif
  char *buf;

#if 0
  if (!sem_ok)
    {
      sem_ok = 1;
      InitSemaphore(&ss);
    }

  ObtainSemaphore(&ss);
#endif

#if 0
  while (!(*(unsigned short *)0xdff016 & (1 << 8))) ;
  while ((*(unsigned short *)0xdff016 & (1 << 8))) ;
#endif

  if (mp = myFindPort("debug.port"))
    {
      op=CreatePort(0,0);
      buf=AllocMem(255,0);

      ms[0].mn_ReplyPort = op;

      sprintf(buf, fmt, a0,a1,a2,a3,a4,a5,a6,a7);
      *(char **)&ms[1] = buf;
  
      PutGetMsg(mp, op, &ms[0]);
      DeletePort(op);
      FreeMem(buf,255);
    }

#if 0
  ReleaseSemaphore(&ss);
#endif
}
#endif

void
print_char()
{
  asm volatile ("moveb d0,a3@+");
}

void
sprintf(char *buf, char *fmt, long arg)
{
  RawDoFmt (fmt, &arg, print_char, buf);
}
