Refactor stdout flushing