Changing main() to state machine