#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
#include <libp.h>

FREELIST *_mallocchains[MEMCHAINS];

BLKHEAD *_allocbloc;
BLKHEAD *_newfree;

#pragma rundown memdelete 5

static void memdelete(void)
{
	BLKHEAD *p = _allocbloc;
	while (p) {
		BLKHEAD *n = p->next;
		_ll_free(p);
		p = n;
	}
}

static int init_block(size_t size)
{
	size_t ns = size+sizeof(BLKHEAD);
	BLKHEAD *nb;
	FREELIST *list ;
	if (ns < ALLOCSIZE)
		ns = ALLOCSIZE;
	nb = _ll_malloc(ns);
	if (!nb)
		return NULL;
	nb->next = _allocbloc;
	_allocbloc = nb;
	list = nb->freemem = nb + 1 ;
	list->size = ns - sizeof(BLKHEAD) ;
	list->next = 0;
	_newfree = nb;
	return 1;
}
static FREELIST *split(FREELIST *p, int size, FREELIST **slist)
{
	FREELIST *rv;
	int ch;
	rv = (FREELIST *)(((char *)p)+size);
	rv->size = p->size - size ;
	rv->next = 0;
	*slist = rv;
	p->size = size ;
 	return ++p;
}
void *malloc(size_t size)
{
	BLKHEAD *head ;
	FREELIST **slist;
	register FREELIST *p;
	register int siz1 ;
	if (!size)
		return NULL;
	size +=3;
	size &= 0xfffffffc;

	siz1 = size + sizeof(FREELIST);

	/* search the chain for reuse */
	slist = &_mallocchains[(siz1 >> 2) % MEMCHAINS];
	while (*slist) {
		p = *slist;
		if (p->size == siz1) {
		 	*slist = p->next;
 			return ++p;
		}
		slist = &p->next;
	}
	/* search the free blocks for free mem */
	head = _newfree ;
	while (head) {
		p = head->freemem ;
		if (p) {
			if (p->size == siz1) {
			 	head->freemem = 0;
 				return ++p;
			}
			else if (p->size > siz1+sizeof(FREELIST))
				return split(p,siz1,&head->freemem);
		}
		head = head->next ;
	}
	/* now get a new block */
	if (!init_block(siz1)) {
		return NULL;
	}
	/* and split it up to get our block */
	p = _newfree->freemem;
	if (p->size == siz1) {
		 	_newfree->freemem = p->next ;
 			return ++p;
	}

	return split(p,siz1,&_newfree->freemem);
}