Refactored for DRY and Mem-leak fix