refactored memory management stuff