#include "ctl_api.h"

// Initialise a memory area
void ctl_memory_area_init(CTL_MEMORY_AREA_t *memory_area,
                          unsigned *memory,
                          unsigned block_size_in_words, // size of the memory block in words
                          unsigned num_blocks)
{
  unsigned i;  
  unsigned en = ctl_global_interrupts_disable();
  *memory_area = memory;
  **memory_area = 0;
  for (i=1;i<num_blocks;i++)
    {
      unsigned *b = memory+(i*block_size_in_words);
      *b = (unsigned)**memory_area;
      **memory_area = (unsigned)b;
    }
  ctl_global_interrupts_set(en);
}

// Allocate a free memory block 
// Returns the block or 0
unsigned *ctl_memory_area_allocate(CTL_MEMORY_AREA_t *memory_area)
{
  unsigned *b;
  unsigned en = ctl_global_interrupts_disable();
  b = *memory_area;
  if (b)
    *memory_area = (unsigned *)*b;
  ctl_global_interrupts_set(en);
  return b;
}

// Return a memory block
void ctl_memory_area_free(CTL_MEMORY_AREA_t *memory_area,
                          unsigned *block)
{
  unsigned en = ctl_global_interrupts_disable();
  *block = (unsigned)(*memory_area);
  *memory_area = block;
  ctl_global_interrupts_set(en);
}

