/* sbrk: emulate Unix sbrk call */
/* by ERS */
/* jrb: added support for allocation from _heapbase when _stksize == -1 
	thanks to Piet van Oostrum & Atze Dijkstra for this idea and
        their diffs. */

/* WARNING: sbrk may not allocate space in continguous memory, i.e.
   two calls to sbrk may not return consecutive memory. This is
   unlike Unix.
*/

#include <osbind.h>
#include <stddef.h>
#include <stdlib.h>
#include <errno.h>

extern void *_heapbase;
extern long _stksize;

static void * HeapAlloc( sz )
long sz ;
{
    char slush [256];
    register void *sp;
    
    sp = (void *)slush;

 /* round up request size next octet */
    sz = (sz + 7) & ~((unsigned long) 7);

    if ( sp < (void *)((size_t)_heapbase + sz) )
    {
	return NULL;
    }
    sp = _heapbase;
    _heapbase = (void *)((size_t)_heapbase + sz);
    _stksize -= (long)sz;
    
    return( sp );
}

void *_sbrk(n)
	long n;
{
  void *rval;

  if(_heapbase != NULL)
  {
      if(n) rval = HeapAlloc(n);
      else  rval = _heapbase;
  }
  else
  {
      rval = (void *) Malloc(n);
  }
  if (rval == NULL) {
      errno = ENOMEM;
      rval = (void *)-1;
  }
  return rval;
}

void *sbrk(x)
int x;
{
	return _sbrk((long)x);
}
