/*
 * DANG_BEGIN_MODULE
 *
 * Holds the ifprintf() routines for DOSEMU
 *
 * DANG_END_MODULE
 *
 * DANG_BEGIN_CHANGELOG
 *
 * $Date: $
 * $Source: $
 * $Revision: $
 * $State: $
 *
 * $Log: $
 *
 * DANG_END_CHANGELOG
 */

#include "dosemu.h"

#include <stdarg.h>

int ifprintf(int flg, const char *fmt,...)
{
  va_list args;
  char buf[1025];
  int i;
  int error_fd;
#if CONFIG_SHOW_TIME > 0
  static int first_time = 1;
  static int SHOW_TIME =  0;
#endif

  if (!flg || !dbg_fd)
    return 0;

  error_fd = fileno(dbg_fd);

#if CONFIG_SHOW_TIME > 0
  if (first_time)  {
    if (getenv("SHOWTIME"))
      SHOW_TIME = 1;
    first_time = 0;
  }
#endif
	
  va_start(args, fmt);
  i = vsprintf(buf, fmt, args);
  va_end(args);

#if CONFIG_SHOW_TIME > 0
  if (SHOW_TIME) {
    struct timeval tv;
    int result;
    char tmpbuf[1024];
    result = gettimeofday(&tv, NULL);
    assert(0 == result);
    sprintf(tmpbuf, "%d.%d: %s", tv.tv_sec, tv.tv_usec, buf);
#else
    sprintf(buf, "%s", buf);
#endif
	
#if CONFIG_SHOW_TIME > 0
    strcpy(buf, tmpbuf);
  }
#endif

  write(error_fd, buf, strlen(buf));
  if (terminal_pipe) {
    write(terminal_fd, buf, strlen(buf));
  }
  return i;
}
