Refactoring state machine (TODO)