refactor command loop