write_stream rewritten functionally