Code refactored but provides incorrect results