this is a bunch of complicated, deeply nested code.  at least factor it out into e.g. a newLeaf() function.  Then it would also be possible to not have to nest so deeply.