Large refactoring of Leaf code