/*
 * Holger Lehmann
 * Krabat Projekt
 */

#include <stdio.h>
#include <errno.h>
#ifndef _MALLOC_INTERNAL
#define _MALLOC_INTERNAL
#endif
#include <malloc.h>
#undef _MALLOC_INTERNAL

/*
 * --------------------------------------
 * sbrk 
 * --------------------------------------
 */

typedef void * caddr_t;
typedef int difference_t;

#define RAMSIZE ( HEAP / BLOCKSIZE )

#ifndef NULL
#define NULL (caddr_t) 0L
#endif

extern caddr_t _end; /* _end is set in the linker command file */

caddr_t sbrk (difference_t nbytes){
  static caddr_t heap_ptr = NULL;
  caddr_t        base;

  kprintf("%s called\n",__PRETTY_FUNCTION__);
  
  if (heap_ptr == NULL) {
    heap_ptr = (caddr_t)&_end;
  }

  kprintf( "%s: Trying to allocate 0x%x bytes of memory.\n" , __PRETTY_FUNCTION__ , nbytes );
  kprintf( "%s: My heap_ptr is 0x%x and _end is 0x%x .\n" , __PRETTY_FUNCTION__ , heap_ptr , &_end );
  kprintf( "%s: dump of heap_ptr + 64 Byte \n" ,  __PRETTY_FUNCTION__ );
  dump(heap_ptr,64);
  kprintf( "%s: dump of _end + 64 Byte \n" ,  __PRETTY_FUNCTION__ );
  dump(&_end,64);
  kprintf( "%s: dump of heap_ptr+RAMSIZE-64 is \n" ,  __PRETTY_FUNCTION__ , ((int)heap_ptr+(int)RAMSIZE-64) );
  dump(((int)&_end+(int)RAMSIZE-64),64);
  
/*   if (((int)RAMSIZE - (int)heap_ptr) >= 0)  */
  if ( (int)heap_ptr < ( (int)RAMSIZE + (int)&_end ) )
    {
      base = heap_ptr;
      heap_ptr += nbytes;
      kprintf("%s: was able to allocate the memory @0x%x\n" , __PRETTY_FUNCTION__ , base );
      return (base);
    } else {
      errno = ENOMEM;
      kprintf("%s: was NOT able to allocate\n" , __PRETTY_FUNCTION__  );
      return ((caddr_t)-1);
    }   
}
