The goal is to minimize as much as possible how much logic is inside flush(). So let's start by moving out obvious stuff. This data can be preformatted before flush().