/*
  --> Initialization / Execution Logging
   -> Copyright 1996 by Jake Stine and Divine Entertainment.
      All Rights Reserved.

 Functions contained within this module are used by all of the DivEnt
 libraries.  These functions can either log messages to display or to
 a specified log file (or both).

 All output to display uses Stdout functions - puts.
 All output to file uses MMIO functions - _mm_fputs.

 If any errors occur during initialization of or during output to the
 logfile, automatic full verbose output to stdout is enabled. 

*/

#include "mmio.h"
#include <string.h>
#include <stdarg.h>


static BOOL verbose = 1;
static FILE *log_file   = NULL;

static CHAR *str;

// Func: Log_Init
// Initializes the system for logging.  The log file and the option of
// verbose output are set here.
//
// logfile - If the log file specified is NULL, no log file will be used.
// If a log file already exists, it is renamed as a .old file.  DO NOT
// specify an extension, a .txt will automatically be attached!
//
// Suggested lognames would be DIVLOG or the like.
//
// Returns 0  if successful.
//         1  if error opening the logfile (in this case, verbose logging to
//            stdout is automatically enabled)

int log_init(CHAR *logfile, BOOL val)
{
   CHAR *backup;
   
   str = (CHAR *)_mm_calloc(512, sizeof(CHAR));

   if(logfile != NULL && logfile[0] != NULL)
   {   if((backup = (CHAR *)_mm_malloc(strlen(logfile)+5)) == NULL)
       {  log_file = NULL;  return 1;  }
       strcpy(backup,logfile);  strcat(backup,".old");
       strcpy(str,logfile);     strcat(str,".txt");
       remove(backup);
       rename(str,backup);
       free(backup);

       if((log_file = _mm_fopen(str,"wb")) == NULL) return 1;
   } else log_file = NULL;

   verbose = val;
   return 0;
}


// Func: Log_Exit
// Closes up the log file.

void log_exit(void)
{
   if(log_file != NULL)
   {  fclose(log_file);
      log_file = NULL;
   }

   if(str!=NULL) free(str);
}


void log_verbose(void)
{
    verbose = 1;
}


void log_silent(void)
{
    verbose = 0;
}


// Func: printlog
// Direct replacement for printf using logging features.  Anything logged
// using this function is only displayed if the user envokes verbose
// initialization.

void printlog(CHAR *fmt, ... )
{
   static va_list argptr;
   ULONG cnt=0;

   va_start(argptr, fmt);
   cnt = vsprintf(str, fmt, argptr);
   str[cnt + 1] = 0;
   va_end(argptr);

   if(log_file!=NULL)
   {  _mm_fputs(log_file,str);
      fflush(log_file);
   }
   if(verbose) puts(str);
}


// Func: printlogv
// Direct replacement for printf using logging features.  Anything logged
// using this function will ALWAYS be displayed to the console.

void printlogv(CHAR *fmt, ... )
{
   static va_list argptr;
   ULONG cnt=0;

   va_start(argptr, fmt);
   cnt = vsprintf(str, fmt, argptr);
   str[cnt + 1] = 0;
   va_end(argptr);

   if(log_file!=NULL)
   {  _mm_fputs(log_file,str);
      fflush(log_file);
   }
   puts(str);
}

