refactor write-tree