Fixed random infinite loop
Cleanup
Added infinite loop check