Fix #10602 and clean up IO code. (rebased)

A rather imperfect rebase, as on `develop` the previous code is different and the actual bug isn't extant. Rebases #966 and should be tested in the same way.