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

                       CSA Library, Free Evaluation Version 2.0.5 
                                       Release: January 22th 1997 

       Class to avoid heap fragmentation.
       It allocates and frees memory in chunks of about 2 Kb and
       does its own administration to deal with the many
       small blocks.


                                           Copyright(c) 1994-1997 
                                                          ComBits 
                                                  The Netherlands 
***********************************************************************/

#ifndef __CSHEAP_H
#define __CSHEAP_H

#include "stdio.h"
#include "cstools.h"
#include "cstypes.h"

class HEAP
{
   U16 size;    // Chunck size
   U16 nr;      // Number of allocations in a page.
   U16 rs;      // Real chunk size;
   U16 pasi;    // Page size;
   U32 nrbl;    // Number of Blocks allocated.
   U16 is_open;

   void *np;    // Next page
   void *fp;    // Chain of full pages.

   typedef struct
   {
     void *n;   // next page
     void *p;   // prev page
     void *e;   // empty chain
     U16  count;// number available
   } pahe;      // Page HEader


protected:
   void connect(void *l,void *r);
   void *new_page(void);
   void unchain(void *&chain,void *p);
   void head_chain(void *&chain,void *p);
   void zap2(void );

public:

   ~HEAP(void) { if (is_open) close(); }
   HEAP(void)  { is_open=FALSE; fp=np=NULL; nrbl=0; size=0; }

////////////////////// Compatibility functions //////////////////////////
#ifndef _CP_003
   // The GNU compiler generates an error on these functions...

   void free(void *p) { vfree(p); }
   void *malloc(void) { return vmalloc(); }
#endif

////////////////////// Init/Creation ////////////////////////////////////
   void init(U16 s,U16 page_size=2048);

////////////////////// Open/Close ///////////////////////////////////////
   void close(void);
   int  open(void);

////////////////////// Malloc/Free //////////////////////////////////////
   void vfree(void *);
   void *vmalloc(void);


   void empty(void );
   void zap(void );
   U32  blocks(void) { return nrbl; }
   void report(FILE *fp,int sub);


};


#endif
