#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <exec/types.h>
#include <exec/io.h>
#include <devices/tpt.h>

#include <dlg/dlg.h>
#include <dlg/Debug.h>

#include <proto/exec.h>
#include <proto/dos.h>
#include <proto/dlg.h>

#include <link/io.h>

#include <pragmas/dlg.h>

#include <private/Version.h>
#define  ObjRev "1"
const UBYTE version[]="\0$VER: DLGDebug " BUILDVER "." ObjRev " ©" COPYRIGHT " by Digerati Dreams "__AMIGADATE__;

void CleanUp(char *);

BPTR            sout;
char          **SA;
struct Library *DLGBase = NULL;
struct MsgPort *dport   = NULL;

/// main()
void main()
{
   struct debug_mess *dmess;

   sout    = Output();

   if (!sout)     CleanUp("No Output Device");

   DLGBase = OpenLibrary(DLGNAME, DLGVERSION);
   if (!DLGBase)  CleanUp("Unable to open dlg.library");

   if (!(dport = CreateMsgPort()))  CleanUp("Unable to open control port");

   dport->mp_Node.ln_Name = DEBUG;
   AddPort(dport);

   do
   {
      WaitPort(dport);

      while((dmess = (struct debug_mess *)GetMsg(dport)))
      {
         char t[32];

         MDate(t);

         switch(dmess->num)
         {
            case     DLG_VISITOR:   AFPrintf(NULL, sout, "%s [VISITOR]    : ",t);               break;
            case     HANDLER_PORT:  AFPrintf(NULL, sout, "%s [HANDLER %s]: ", t, dmess->port);  break;
            case     RM_PORT:       AFPrintf(NULL, sout, "%s [RESMAN]     : ", t);              break;
            default:                AFPrintf(NULL, sout, "%s [UNKNOWN]    : ", t);              break;
         }

         if (dmess->str)
            AFPrintf(NULL, sout, " %s\n", dmess->str);
         else
            AFPrintf(NULL, sout, "\n");

         ReplyMsg((struct Message *)dmess);
      }
   } while(TRUE);

   CleanUp(NULL);
}
//-
/// CleanUp
void CleanUp(char *s)
{
   if (DLGBase)  CloseLibrary(DLGBase);

   if (dport)
   {
      RemPort(dport);
      DeleteMsgPort(dport);
   }

   if (s && sout)
   {
      Write(sout, "\n Error: ", 9);
      Write(sout,  s,    strlen(s));
      Write(sout, "\n\n",       2);
   }

   exit(s?5:0);
}
//-
