Fix #10602 and clean up IO code.
Merge pull request #966 from mtbc/trac-10602

Fix #10602 and clean up IO code.