/*
 * memory.c
 *
 * Replacement memory management routines (using pools)
 *
 * $Id :$
 * $Log:$
 *
 */

#include "defs.h"
#include "exit.h"
#include "memory.h"

#include <exec/memory.h>
#include <proto/exec.h>


/*******************************************************************/

/*
 * #define MEMORY_LOG to list all allocations to a file
 */

#ifdef MEMORY_LOG

#include <dos/dos.h>
#include <proto/dos.h>

#ifndef MEMORY_LOG_FILE
#define MEMORY_LOG_FILE "t:memory_log.txt"
#endif

static BPTR LogFile;

/*
 * MemLog_Dispose()
 *
 * Close the memory log. Called automatically at exit()
 */

static VOID
MemLog_Dispose( VOID )
{
    Close( LogFile );
}


#endif /* MEMORY_LOG */

/*******************************************************************/


/*
 * private stuff
 */

static APTR MyPool;

#define MYPOOL_MEM_REQUIREMENTS     MEMF_ANY | MEMF_CLEAR
#define MYPOOL_PUDDLE_SIZE          2048L
#define MYPOOL_THRESH_SIZE          2048L

/*******************************************************************/


/*
 * MyPool_Dispose()
 */

static VOID
MyPool_Dispose( VOID )
{
    DeletePool( MyPool );

    return;
}
        

/*
 * MyPool_New()
 */

VOID
_INIT_7_MyPool_New( VOID )
{
    if( MyPool = CreatePool( MYPOOL_MEM_REQUIREMENTS, MYPOOL_PUDDLE_SIZE, MYPOOL_THRESH_SIZE ) )
        atexit( MyPool_Dispose );
    else
        MyExit( "Unable to allocate memory pool" );

#ifdef MEMORY_LOG

    if( LogFile = Open( MEMORY_LOG_FILE, MODE_NEWFILE ) )
        atexit( MemLog_Dispose );
    else
        MyExit( "Unable to open memory log file:" MEMORY_LOG_FILE );

#endif /* MEMORY_LOG */

    return;
}


/*
 * Memory_Alloc()
 */

APTR
Memory_Alloc( ULONG size )
{
#ifdef MEMORY_LOG

    APTR memory = AllocPooled( MyPool, size );
    FPrintf( LogFile, "Got   %6ld bytes at %08lx\n", size, memory );
    return memory;

#else

    return AllocPooled( MyPool, size );

#endif
}


/*
 * Memory_Free()
 */

VOID
Memory_Free( APTR memory, ULONG size )
{
#ifdef MEMORY_LOG

    FPrintf( LogFile, "Freed %6ld bytes at %08lx\n", size, memory );

#endif

    FreePooled( MyPool, memory, size );
}

