added edge cases & refactored