use write(..) and then only flush if the next if block not hit.