#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>

int suppress_debug = (0!=0);
int checked = 0;

#ifndef LOGFILE
#define LOGFILE "/tmp/debugf.log"
#endif

void debugf(char *s, ...)
{
  /* OK, I'm going to nail this damn bug for once and all... */
  /* Time to size the string by vfprint'ing it to /dev/null... */
  FILE *errfile;
  int string_length;
  static char *buff = NULL;
  va_list ap;          
  

  if (checked == 0) {
    checked = 1;
    errfile = fopen(LOGFILE, "r");
    if (errfile == NULL) {
      /* Only want to log if file exists already... */
      suppress_debug = (0==0);
    } else {
      fclose(errfile);
    }
  }

  va_start(ap, s);
  
  {
    FILE *nullfile;
    
    nullfile = fopen("/dev/null", "w");
    if (nullfile == NULL) {
      errfile = fopen(LOGFILE, "a");
      if (errfile != NULL) {
        fprintf(errfile, "Major error - cannot open /dev/null\n");
        fflush(errfile);
        fclose(errfile);
      }
      exit(1);
    }
    string_length = vfprintf(nullfile, s, ap);
    fclose(nullfile);
    buff = malloc(string_length+1);
    if (buff != NULL) vsprintf(buff, s, ap);
  }
  va_end(ap);
  
  /* Suppress logging to file, but still allow in window if present */
  
  if (suppress_debug) {
    return;
  }

  /*fprintf(stderr, "%s", buff);*/
  errfile = fopen(LOGFILE, "a");
  if (errfile != NULL) {
    if (buff != NULL) fprintf(errfile, "%s", buff);
    if (buff == NULL) fprintf(errfile, "debugf: could not allocate %d byte buffer\n", string_length);
    fflush(errfile);
    fclose(errfile);
  }
  if (buff != NULL) free(buff); buff = NULL;
}

