Move read loop into its own method and fix bug.