Refactor some common code and added comments. All submit tests passed pre-commit.