char *sbrk(int inc)
{
	char *r;
	if (g->lastbrk == NULL) {
		g->lastbrk = (char*)brk(0);
		g->savebrk = g->lastbrk;
	}
	r = g->lastbrk;
	g->lastbrk = (char*)brk(g->lastbrk + inc);
	if (g->lastbrk != (r + inc))
		return (char*)-1;
	return r;
}

/* morecore: ask system for more memory */
static Header *morecore(unsigned nu)
{
	char *cp, *sbrk(int);
	Header *up;

	if (nu < NALLOC)
		nu = NALLOC;
	cp = sbrk(nu * sizeof(Header));
	if (cp == (char *) -1)				/* no space at all */
		return NULL;
	up = (Header *) cp;
	up->s.size = nu;
	free((void *)(up+1));
	return g->freep;
}

/* malloc: general-purpose storage allocator */
static void *malloc(unsigned nbytes)
{
	Header *p, *prevp;
	unsigned nunits;

	nunits = (nbytes+sizeof(Header)-1)/sizeof(union header) + 1;
	if ((prevp = g->freep) == NULL) {			/* no free list yet */
		g->base.s.ptr = g->freep = prevp = &g->base;
		g->base.s.size = 0;
	}
	for (p = prevp->s.ptr; ; prevp = p, p = p->s.ptr) {
		if (p->s.size >= nunits) {		/* big enough */
			if (p->s.size == nunits) 	/* exactly */
				prevp->s.ptr = p->s.ptr;
			else {				/* allocate tail end */
				p->s.size -= nunits;
				p += p->s.size;
				p->s.size = nunits;
			}
			g->freep = prevp;
			return (void *)(p+1);
		}
		if (p == g->freep)				/* wrapped around free list */
			if ((p = morecore(nunits)) == NULL)
				return NULL;		/* none left */
	}
}

/* free: put block ap in free list */
static void free(void *ap)
{
	Header *bp, *p;

	bp = (Header *)ap - 1;				/* point to block header */
	for (p = g->freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr)
		if (p >= p->s.ptr && (bp > p || bp < p->s.ptr))
			break;				/* freed block at start or end of arena */

	if (bp + bp->s.size == p->s.ptr) {		/* join to upper nbr */
		bp->s.size += p->s.ptr->s.size;
		bp->s.ptr = p->s.ptr->s.ptr;
	} else
		bp->s.ptr = p->s.ptr;
	if (p + p->s.size == bp) {			/* join to lower nbr */
		p->s.size += bp->s.size;
		p->s.ptr = bp->s.ptr;
	} else
		p->s.ptr = bp;
	g->freep = p;
}
