Refactored patch function