This re-applies Gábor's stream closing work with some additional fixes