fix stream closing sequence