void ComponentBuilder::updateChildComponents (Component& parent, const ValueTree& children)
{
    using namespace ComponentBuilderHelpers;

    const int numExistingChildComps = parent.getNumChildComponents();

    Array <Component*> componentsInOrder;
    componentsInOrder.ensureStorageAllocated (numExistingChildComps);

    {
        OwnedArray<Component> existingComponents;
        existingComponents.ensureStorageAllocated (numExistingChildComps);

        int i;
        for (i = 0; i < numExistingChildComps; ++i)
            existingComponents.add (parent.getChildComponent (i));

        const int newNumChildren = children.getNumChildren();
        for (i = 0; i < newNumChildren; ++i)
        {
            const ValueTree childState (children.getChild (i));

            ComponentBuilder::TypeHandler* const type = getHandlerForState (childState);
            jassert (type != nullptr);

            if (type != nullptr)
            {
                Component* c = findComponentWithID (existingComponents, getStateId (childState));

                if (c == nullptr)
                    c = createNewComponent (*type, childState, &parent);

                componentsInOrder.add (c);
            }
        }

        // (remaining unused items in existingComponents get deleted here as it goes out of scope)
    }

    // Make sure the z-order is correct..
    if (componentsInOrder.size() > 0)
    {
        componentsInOrder.getLast()->toFront (false);

        for (int i = componentsInOrder.size() - 1; --i >= 0;)
            componentsInOrder.getUnchecked(i)->toBehind (componentsInOrder.getUnchecked (i + 1));
    }
}