Added private writeToFile() method to reduce redundancy.
Refactored some of flush(). Added writeToFile() and writeNewElement()
methods.