Updated to handle corner cases