Working, but sometimes causes an infinite loop