More robust state management. Refactoring some code.