Fix bad/missing EOF checking, one could cause an infinite loop.

Also added a unit test that tests the infinite loop case.