Modify search algorithm to handle edge cases better