// secmem.c
// written by Stefan Pfeiffer, DL1ELY, 970818
// last modification: 970818
// (C) 1997 by DL1ELY

#include "secmem.h"
#include <mem.h>
#include <dos.h>
#include <alloc.h>

#define LIST_SIZE 2048


void *ptr_list[LIST_SIZE];
unsigned size_list[LIST_SIZE];
unsigned long alloc_cnt = 0;

void sec_start(void)
{
   memset(ptr_list,0,LIST_SIZE*sizeof(void *));
   memset(size_list,0,LIST_SIZE*sizeof(unsigned));
   alloc_cnt = 0;	   
};


void sec_list_full(void)
{
   while(1)
   {
      sound(800);
      delay(100);
      nosound();
      delay(100);
      sound(800);
      delay(100);
      nosound();
      delay(100);
      sound(800);
      delay(300);
      nosound();
      delay(100);
      sound(800);
      delay(100);
      nosound();
      delay(500);
   };
};

void sec_mem(void)
{
   while(1)
   {
      sound(800);
      delay(300);
      nosound();
      delay(100);
      sound(800);
      delay(300);
      nosound();
      delay(500);
   };
};

void sec_unknown(void)
{
   while(1)
   {
      sound(800);
      delay(100);
      nosound();
      delay(100);
      sound(800);
      delay(100);
      nosound();
      delay(100);
      sound(800);
      delay(300);
      nosound();
      delay(100);
      sound(800);
      delay(300);
      nosound();
      delay(100);
      sound(800);
      delay(100);
      nosound();
      delay(100);
      sound(800);
      delay(100);
      nosound();
      delay(500);
   };
};

void *sec_alloc(unsigned size)
{
   unsigned i;
   void *res;
   
   res = malloc(size);
   if(res)
   {
      for(i=0;(i<LIST_SIZE)&&ptr_list[i];i++);
      if(i<LIST_SIZE)
      {
	 alloc_cnt++;      	
         ptr_list[i] = res;
         size_list[i] = size;
      }
      else sec_list_full();
   }
   else sec_mem();
   
   return(res);
};

      
void sec_free(void *ptr)
{
   unsigned i;
   
   for(i=0;(i<LIST_SIZE)&&(ptr!=ptr_list[i]);i++);
   
   if(i<LIST_SIZE)
   {
      alloc_cnt--;
      ptr_list[i] = NULL;
      size_list[i] = 0;
      free(ptr);
   }
   else sec_unknown();
};


   