refine code in MasterLoop
- break into small functions --> easy to follow