Refactored the patch by following tips from code review