refactor and handle edge cases better