Fixing issue that enters infinite loop under certain conditions