refactor code following chen3feng's comments