refactored grade function