func: much more robust WriteBufferIfNecessary