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

/* function to output debugging information */
void debug(char *fmt, ...)
{
   const int headlen = strlen("[ERROR (client XXXX [X])]: ") + 1;

   va_list args;

   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) - headlen, fmt, args);
   va_end(args);

   if (debugging == 1)
   {
      if (strstr(debugbuf, "ERROR") == NULL)
      {
         if ((curClient >= 0) && (clients[curClient].ID > 0) &&
             (clients[curClient].ID <= 9999))
         {
            if (clients[curClient].numSubIDs > 0)
            {
               printf("[DEBUG (client %04d [%d])]: %s", clients[curClient].ID, 
                      clients[curClient].numSubIDs, debugbuf);

               if (dblogfd <= 0) return;

               snprintf(bigbuf, sizeof(bigbuf)-1, 
                        "[DEBUG (client %04d [%d])]: %s", 
                        clients[curClient].ID, clients[curClient].numSubIDs, 
                        debugbuf);

               (void)write(dblogfd, bigbuf, strlen(bigbuf));

            }

            else
            {
               printf("[DEBUG (client %04d)]: %s", clients[curClient].ID, 
                      debugbuf);

               if (dblogfd <= 0) return;

               snprintf(bigbuf, sizeof(bigbuf) - 1, 
                        "[DEBUG (client %04d)]: %s", clients[curClient].ID, 
                        debugbuf);

               (void)write(dblogfd, bigbuf, strlen(bigbuf));
            }
         }

         else
         {
            printf("[DEBUG (pid %d)]: %s", getpid(), debugbuf);

            if (dblogfd <= 0) return;

            snprintf(bigbuf, sizeof(bigbuf)-1, "[DEBUG (pid %d)]: %s", 
                     getpid(), debugbuf);

            (void)write(dblogfd, bigbuf, strlen(bigbuf));
         }
      }

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

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