WIP: update tree cache in write_tree

I think the error handling still needs work to ensure the right entries are freed.