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

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

   time_t tm;

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

   int headlen = strlen("[ERROR (pid XXXXX) - 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 (((errmsg[0] == '\0') || (errmsg[0] == '\n')) && 
       (isprint((int)errmsg[1]) == 0))
   {
      debug("bad data in error message... returning\n");
      return;
   }

   (void)sprintf(errbuf, "[ERROR (pid %d) - %s", (int)getpid(), ctime(&tm));

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

   errbuf[sizeof(errbuf)-2] = '\n';
   errbuf[sizeof(errbuf)-1] = '\0';

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

      exit(ERROR);
   }

   if (strstr(errbuf, "\n\n") == NULL) (void)write(errlogfd, "\n", 1);
   if (debugging == 1) debug("[ERROR (pid %d)]: %s", (int)getpid(), errmsg);
}
