start to handle control flow, and some refactoring