public function updateDefinition(WorkflowDefinition $definition)
    {
        $existingActions = array();

        $existing = $definition->Actions()->column('Title');
        $structure = array_keys($this->structure);

        $removeNames = array_diff($existing, $structure);

        foreach ($definition->Actions() as $action) {
            if (in_array($action->Title, $removeNames)) {
                $action->delete();
                continue;
            }
            $existingActions[$action->Title] = $action;
        }

        $actions = array();
        $transitions = new ArrayObject;
        $sort = 1;
        // now, go through the structure and create/realign things
        foreach ($this->structure as $relationName => $relationTemplate) {
            $isAction = isset($relationTemplate['type']);
            $isUsers = ($relationName == 'users');
            $isGroups = ($relationName == 'groups');

            if ($isAction) {
                $action = null;
                if (isset($existingActions[$relationName])) {
                    $action = $existingActions[$relationName];
                } else {
                    $action = $this->createAction($relationName, $relationTemplate, $definition, $transitions);
                }

                // add a sort value in!
                $action->Sort = $sort++;
                $action->write();

                $actions[$relationName] = $action;

                $newTransitions = $this->updateActionTransitions($relationTemplate, $action);
                foreach ($newTransitions as $t) {
                    $transitions->append($t);
                }
            }
            // Process users on WorkflowDefinition from the template
            if ($isUsers) {
                $this->createUsers($relationTemplate, $definition, true);
            }
            // Process groups on WorkflowDefinition from the template
            if ($isGroups) {
                $this->createGroups($relationTemplate, $definition, true);
            }
        }

        foreach ($transitions as $transition) {
            if (isset($actions[$transition->Target])) {
                $transition->NextActionID = $actions[$transition->Target]->ID;
            }
            $transition->write();
        }

        // Set the version and do the write at the end so that we don't trigger an infinite loop!!
        $definition->Description = $this->getDescription();
        $definition->TemplateVersion = $this->getVersion();
        $definition->RemindDays = $this->getRemindDays();
        $definition->Sort = $this->getSort();
        $definition->write();
    }