It's tricky to get this right, but basically we want to read if there is something to read; if not, we want to check for EOF.