Refactor main into state.