/*
 * Copyright 2003 Sun Microsystems Inc.
 *
 * This is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
 * Boston, MA 02111-1307, USA.
 *
 * Authors: Karl Park <karl.park@sun.com>
 */

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


static FILE *fp = NULL;

void
KOLE_LOG (LOGDEST dest, char *fmt, ...)
{
  char *fname;
  int strdup_was_called = 0;
  
  va_list va;
  char buffer[1024];
  va_start (va, fmt);
  vsnprintf (buffer, sizeof (buffer), fmt, va);
  va_end (va);

  switch (dest){
  case LOGDEST_STDOUT:
    fprintf (stdout, "%s\n", buffer);
    break;
  case LOGDEST_STDERR:
    fprintf (stderr, "%s\n", buffer);
    break;
  case LOGDEST_FILE:
    fname = (char *)getenv ("LOGFILE");
    if (!fname){
      fname = (char *) strdup (LOGFILE);
      strdup_was_called = 1;
    }
    fp = fopen (fname, "a");
    
    if (!fp){
      fprintf (stderr, "error writing log to file %s\n", fname);
      fprintf (stderr, "the error msg was\n");
      fprintf (stderr, "%s\n", buffer);
      break;
    }
    fprintf (fp, "%s\n", buffer);
    fclose (fp);
    if (strdup_was_called)
      free (fname);
    break;
  default:
    break;
  }
}

#ifdef TEST_RUN

int
main (int argc, char **argv)
{
  int age = 5;
  char *name = "jaehee";
  
  KOLE_LOG (LOGDEST_FILE, "My daughter, %s is %d years old", name, age);
  return 0;
}

#endif

