Handle output stream closure better

This replaces #195, which we let get stale and so required more changes.