Merge iostream fixes, mostly by Richard Smith.
Fixes #3612, #3311, #2094, #3010, #2894, #3011, #3352, #3505.