Refactor state machine building