// Logging, this will probably get more complex
// By: Odis

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

// for exists_file (struct stat)
#include <sys/types.h>
#include <sys/stat.h>

#include "log.h"

using namespace std;

// Plain text function: creates new line with #, accepts multiple arguments
void glog(const char *txt, ...)
{
  FILE *fp;
  char buf[3072];
  char file_name[128];
  static int log_num = 0;
  va_list args;

  va_start(args, txt);
  vsprintf(buf, txt, args);
  va_end(args);

  /* if the log directory doesnt exist, create it */
  if ( exists_file("../log") == 0 )
   system( "mkdir log" );

  /* print the fname */
  sprintf( file_name, "../log/log.txt" );

  /* try to open logfile */
  if ((fp = fopen(file_name, "a")) == NULL)
    return;

  if ( log_num == 0 )
  {
    fprintf( fp, "\n\n\n\n\n------------------------\n" ); /* give us a few spaces inbetween */
    log_num++;
  }
  else
    log_num++;


  fprintf(fp, "%d.  %s\n", log_num, buf);
  fclose(fp);
}

// Does a file exist with filen as the file name?
bool exists_file( char *filen )
{
  struct stat fst;

  if ( stat( filen, &fst) == -1 )
   return false; /* file doesnt exist! */

  return true;
}