Refactor loose state machine