It would be a lot clearer if this function took a filename as an argument instead of reading from stdin.