refactored the algorithm to remove the nested 'if'