Fix bug in the writing function