Use the new HttpResponse.HeadersSent property and apply minor changes