Refactored code to use state machines for entities