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

/* function to report an error to the error file */
void error(char *fmt, ...)
{
   int res = 0;
   va_list args;

   time_t tm;

   char errmsg[MAXREADSIZE];
   char errbuf[MAXREADSIZE];

   int headlen = strlen("[ERROR (client XXXX [X]) - "
                        "XXX XXX XX XX:XX:XX XXXX]: ");

   tm = time(NULL);

   memset(errmsg, 0, sizeof(errmsg));
   memset(errbuf, 0, sizeof(errbuf));

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

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

   if ((curClient < 0) || (clients[curClient].ID <= 0) ||
       (clients[curClient].ID > 9999))
      (void)sprintf(errbuf, "[ERROR (pid %d) - %s", getpid(), ctime(&tm));

   else
   {
      if (clients[curClient].numSubIDs > 0)
         (void)sprintf(errbuf, "[ERROR (client %04d [%d]) - %s", 
                       clients[curClient].ID, clients[curClient].numSubIDs,
                       ctime(&tm));

      else
         (void)sprintf(errbuf, "[ERROR (client %04d) - %s", 
                       clients[curClient].ID, ctime(&tm));
   }

   errbuf[strlen(errbuf)-1] = '\0';
   (void)strcat(errbuf, "]:\n");

   errbuf[sizeof(errbuf)-2] = '\n';
   errbuf[sizeof(errbuf)-1] = '\0';
   (void)strcat(errbuf, errmsg);

   res = write(errlogfd, errbuf, strlen(errbuf));
   if ((res == 0) || ((res == ERROR) && (errno > 0)))
   {
      (void)fprintf(stderr, "unable to write to the error log: %s\n\n",
                    strerror(errno));

      exit(ERROR);
   }

   if (debugging == 1)
   {
      if ((curClient < 0) || (clients[curClient].ID <= 0) ||
          (clients[curClient].ID > 9999))
         debug("[ERROR (pid %d)]: %s", getpid(), errmsg);

      else
      {
         if (clients[curClient].numSubIDs > 0)
            (void)sprintf(errbuf, "[ERROR (client %04d [%d])]: %s\n", 
                          clients[curClient].ID, clients[curClient].numSubIDs, 
                          errmsg);

         else
            (void)sprintf(errbuf, "[ERROR (client %04d)]: %s\n", 
                          clients[curClient].ID, errmsg);
      }
   }
}
