partial refactoring of memory management. setup now only contain
defensive code.