
#ifdef MACHINE_AMIGA
 #include <clib/exec_protos.h>
 #include <pragmas/exec_pragmas.h>
 #include <exec/memory.h>
#endif

/***********************************************************************************
** Function: FreeSoundMem()
*/

LIBFUNC void LIBFreeSoundMem(mreg(__d0) APTR MemBlock)
{
  FreeMemBlock(MemBlock);
}

/***********************************************************************************
** Function: AllocSoundMem()
** Synopsis: Memory = AllocSoundMem(Size, Flags);
**
** Allocates memory that can be used to play audio samples.
*/

#define MEMHEADER    20             /* 16 bytes at start, 4 at end */
#define MEMF_REVERSE (1L<<18)
#define CODE_MEMH    0x4D454D48L
#define CODE_MEMT    0x4D454D54L

LIBFUNC APTR LIBAllocSoundMem(mreg(__d0) LONG Size, mreg(__d1) LONG Flags)
{
  LONG *Memory;
  LONG *EndMemory;
  struct DPKTask *Task;
  WORD i;
  LONG AFlags;

  if (Size) {
     Size  += MEMHEADER;           /* ++MEMHEADER */
     AFlags = MEMF_CHIP;

     if ((Flags & MEM_NOCLEAR) IS NULL) {
        AFlags |= MEMF_CLEAR;
     }

     if (Size > 32767) {           /* Large chunks go to the other side of the  */
        AFlags |= MEMF_REVERSE;    /* memory boundary to prevent fragmentation. */
     }

     /* Allocate the memory using the exec.library
     ** routines.
     */

     if (Memory = AllocMem(Size,AFlags)) {
        EndMemory    = (LONG *)(((BYTE *)Memory)+Size-4);
        EndMemory[0] = CODE_MEMT;

        i = NULL;
        Memory[i++] = NULL;             /* Empty */
        Memory[i++] = Size-MEMHEADER;   /* Remember size */
        if (Flags & MEM_UNTRACKED) {    /* Tracking key */
           Memory[i++] = NULL;
        }
        else {
           Memory[i++] = AddTrack(RES_MEMORY,(LONG)(Memory+4),LIBFreeSoundMem);
        }
        Memory[i++] = CODE_MEMH;        /* Memory header */

        if (Task = FindDPKTask()) {     /* Remember memory totals */
           Task->TotalSound += Size;
        }

        if (GVBase->Debug) GVBase->Debug->AllocSoundMem(Size,Flags,Memory+i);
        StepBack();
        return(Memory+i);
     }
     else DPrintF("!AllocSoundMem:","Could not allocate memory space.");
  }
  else DPrintF("!AllocSoundMem:","You requested a memory size of NULL.");

  return(NULL);
}

