close the stream properly