/*
 * $Header: /home/gene/library/website/docsrc/httpxtran/src/RCS/debug.c,v 395.1 2008/04/20 17:25:51 gene Exp $
 *
 * Copyright (c) 2004--2006 Gene Michael Stover.  All rights reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 * 
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL GENE MICHAEL STOVER BE LIABLE FOR
 * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
 * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 * 
 * Except as contained in this notice, the name of Gene Michael Stover
 * shall not be used in advertising or otherwise to promote the sale, use
 * or other dealings in this Software without prior written authorization
 * from Gene Michael Stover.
 */

#include "this.h"

/*
 */
static BOOL S_isEnabled = FALSE;

void
DEBUG_Enable (BOOL isEnabled)
{
  S_isEnabled = isEnabled;
}

BOOL
DEBUG_IsVerbose () {
  return S_isEnabled;
}

void
DEBUG_Print (char file[], int line, char fmt[], ...)
{
  va_list ap;

  if (DEBUG_IsVerbose ()) {
    fprintf (stderr, "\n%s:%d:",
	     strrchr (file, '\\') ? strrchr (file, '\\') + 1 : file,
	     line);
    va_start (ap, fmt);
    vfprintf (stderr, fmt, ap);
    va_end (ap);
  }
}

void
DEBUG_PrintError (char file[], int line, char moo[], long error)
{
#if IS_UNIX
  DEBUG_Print (file, line, " %s: %s", moo, strerror (error));
#endif

#if IS_WINDERS
  DWORD           flags;
  LPVOID          lpMsgBuf;

  if (DEBUG_IsVerbose ()) {
    flags = FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM |
      FORMAT_MESSAGE_IGNORE_INSERTS;
    if (FormatMessage (flags, NULL, error,
		       MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
		       (LPTSTR) & lpMsgBuf, 0, NULL)) {
      DEBUG_Print (file, line, " %s: %s", moo, lpMsgBuf);
      LocalFree (lpMsgBuf);
    }
  }
#endif
}

void
DEBUG_PrintLastError (char file[], int line, char moo[])
{
  DEBUG_PrintError (file, line, moo,
#if IS_UNIX
		    errno
#endif
#if IS_WINDERS
		    GetLastError ()
#endif
		    );
}

/* --- end of file --- */
