Fix bug causing infinite loop