refactored & updated to handle corner cases