#ifndef _DWC_ERR_C
#define _DWC_ERR_C

/*--------------------------------------------------------------------------
 *  Copyright (c) 2001-2004 Igor Daniloff. 
 *	All rights reserved.
 *
 * By using this file, you agree to the terms and conditions set
 * forth in the LICENSE file which can be found at this directory.
 *------------------------------------------------------------------------*/
 
#ifndef lint
static const char rcsid[] = "$Id: dwc_err.c,v 1.19 2005/09/21 09:20:43 asv Exp $";
#endif

#if defined(__WIN32_DW)
#include <windows.h>
#include "dw_winlib.h"
#endif /* __WIN32_DW */
#if defined(__UNIX_DW)
#include <unistd.h>
#include <string.h>
#endif /* __UNIX_DW */
#include <stdlib.h>
#include "dwc_err.h"
#include "dwc_log.h"

DWC_mutex_t  err_mutex = INVALID_MUTEX;

/* -------------------------------------------------- */
dwc_string_t stdlib_error(int code)
{
#if defined(__WIN32_DW)
    static char         err[100];
#endif /* __WIN32_DW */
    dwc_string_t        perr;

    if( dwc_mutex_lock( err_mutex ) )
    {
#if defined(__WIN32_DW)
        FormatMessage( FORMAT_MESSAGE_FROM_SYSTEM, NULL, code, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), err, sizeof(err)-1, NULL ); 
        perr = err;
#endif /* __WIN32_DW */
#if defined(__UNIX_DW)
        perr = strerror(code);
#endif /* __UNIX_DW */
        if( !dwc_mutex_unlock( err_mutex ) )
        {
            printLib( DW_LL_ERROR, "dwlib: stdlib_error: cannot unlock mutex" );
        }
    }
    else
    {
        printLib( DW_LL_ERROR, "dwlib: stdlib_error: cannot lock mutex" );
        perr = "error get stdlib error string";
    }
    return perr;
}

#if defined(DW_DEBUGMALLOC)
/* -------------------------------------------------- */
dwc_string_t dw_strdup( char* str, char* file, int line )
{
    dwc_string_t ptr = strdup( str );
    if( ptr )    
        printLib( DW_LL_DEBUG, "[%d]: %x was allocated %d bytes in %s(%d) (by stdup)", getpid(), ptr, strlen(str), file, line );
    else
        printLib( DW_LL_DEBUG, "[%d]: was fail allocated %d bytes in %s(%d) (by strdup)", getpid(), strlen(str), file, line );    
    return ptr;        
}

/* -------------------------------------------------- */
dwc_pointer_t dw_malloc( int size, char* file, int line )
{
    dwc_pointer_t ptr = malloc(size);
    if( ptr )    
        printLib( DW_LL_DEBUG, "[%d]: %x was allocated %d bytes in %s(%d) (by malloc)", getpid(), ptr, size, file, line );
    else
        printLib( DW_LL_DEBUG, "[%d]: was failed to allocate %d bytes in %s(%d) (by malloc)", getpid(), size, file, line );    
    return ptr;        
}

/* -------------------------------------------------- */
dwc_void_t dw_free( void* ptr, char* file, int line )
{
    if( ptr )    
        printLib( DW_LL_DEBUG, "[%d]: %x was freed from %s(%d)", getpid(), ptr, file, line );
    else
        printLib( DW_LL_DEBUG, "[%d]: null was passed from %s(%d)", getpid(), file, line );    
    free( ptr );
}
#endif /* DEBUGMALLOC */

#endif /* _DWC_ERR_C */
