This is pretty large. I would advocate to extract this to a `SynchronizedStreamWriter` class or something.