Revert "Revert "A little memory management changes etc""

This reverts commit a30880e82d2d4ee7008d8efe0f7e555abe90aee3.