refactored a bit to remove some uninitialized state etc