Fix the typo close() instead of closeElement() (bug).
Added flush() where needed (so this is not lost in case of unexpected exception).