/* $Header: pd:zvmrcs/debug.c,v 1.1 1993/04/07 18:47:36 rvillari Exp $ */
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include <clib/exec_protos.h>
#include <ctype.h>
#include <exec/memory.h>
#include "debug_proto.h"

#include "logger.h"

struct MsgPort* getPort(char* port) {
  struct MsgPort* retVal;
  Forbid();
  retVal = FindPort(port);
  Permit();
  return retVal;
}

void sendErrorToLogger(char* error) {
  struct MsgPort* loggerPort = getPort("LOGGERMP");

  struct DLMsg* loggerMsg = (struct DLMsg*)AllocMem(sizeof(struct DLMsg), MEMF_PUBLIC | MEMF_CLEAR);

  if (loggerPort && loggerMsg) {
    loggerMsg->message.mn_ReplyPort = 0;
    loggerMsg->message.mn_Length = sizeof(struct DLMsg);
    strncpy(loggerMsg->error, error, sizeof(loggerMsg->error) - 5);
    loggerMsg->error[sizeof(loggerMsg->error) - 1] = '\0';
    PutMsg(loggerPort, (struct Message*)loggerMsg);

    loggerMsg = 0; /* assume that the logger takes care of deleting this msg */
  }

  if (loggerMsg) FreeMem(loggerMsg, sizeof(struct DLMsg));
}

void showError(char type, char* string, ...) {
  static int gotDebugFlags = 0;
  static char debugFlags[10];
  char debug[200];
  va_list arglist;

  if (!gotDebugFlags) {
    char* e = getenv("AVMDEBUGFLAGS");
    if (!e) strcpy(debugFlags, "exci"); /* errors, extra debug, commands/responses, information */
    else strcpy(debugFlags, e);
    gotDebugFlags = 1;
  }

  if (strchr(debugFlags, type)) {
    va_start(arglist, string);
    vsprintf(debug, string, arglist);
    va_end(arglist);

    sendErrorToLogger(debug);
  }
}

