Added some optimizations and precautions against getting stuck.