Refactored the sum function