#include "headers.h" /* has all the important stuff */

/* function to output debugging information */
void debug(char *fmt, ...)
{
   va_list args;
   const int headlen = strlen("[DEBUG (pid XXXXX)]: ") + 1;

   char debugbuf[MAXREADSIZE];
   char bigbuf[MAXREADSIZE + headlen];


   if (debugging != 1) return;

   memset(bigbuf, 0, sizeof(bigbuf));
   memset(debugbuf, 0, sizeof(debugbuf));

   va_start(args, fmt);
   (void)vsnprintf(debugbuf, sizeof(debugbuf) - 1, fmt, args);
   va_end(args);

   debugbuf[sizeof(debugbuf)-1] = '\0';

   if (((debugbuf[0] == '\n') || (debugbuf[0] == '\0')) && 
       (isprint((int)debugbuf[1]) == 0)) return;

   if (debugging == 1)
   {
      if (strncmp(debugbuf, "[ERROR", 6) != 0)
      {
         (void)printf("[DEBUG (pid %d)]: %s", (int)getpid(), debugbuf);

         if (dblogfd <= 0) return;

         snprintf(bigbuf, sizeof(bigbuf)-1, "[DEBUG (pid %d)]: %s", 
                  (int)getpid(), debugbuf);
         
         (void)write(dblogfd, bigbuf, strlen(bigbuf));
      }

      else
      {
         (void)printf("%s", debugbuf);

         if (dblogfd <= 0) return;
         (void)write(dblogfd, debugbuf, strlen(debugbuf));
      }
   }
}
