Tidied up code for building trees.