Various small fixes, improvements and refactorings of tree generation code.