Fix logic bugs in stream reading