Add check for EOF to prevent infinite loop

Fixes #299