cleaning up, saving state, and a bit more refactoring