/// <summary>
        ///   Solves all sub tree reference tasks and replaces them by real references to the sub tree.
        /// </summary>
        /// <param name="tree"> Tree in which to solve references. </param>
        /// <returns> Task to use instead of the passed one. </returns>
        private ITask SolveReferences(ITask tree)
        {
            if (tree == null)
            {
                return(tree);
            }

            // Check if root is reference.
            if (tree is SubTreeReference)
            {
                SubTreeReference subTreeReference = tree as SubTreeReference;

                // Resolve reference.
                ITask treeReference = this.SolveReference(subTreeReference);

                return(treeReference);
            }

            // Find sub tree reference tasks in tree.
            ICollection <TaskNode> referenceNodes = new List <TaskNode>();
            TaskNode rootNode = new TaskNode {
                Task = tree
            };

            tree.FindTasks(rootNode, task => task is SubTreeReference, ref referenceNodes);

            // Replace tasks in found nodes by referenced tree.
            foreach (TaskNode referenceNode in referenceNodes)
            {
                SubTreeReference subTreeReference = referenceNode.Task as SubTreeReference;
                if (subTreeReference == null)
                {
                    throw new Exception(
                              "Searched for SubTreeReference nodes, but found a task which is no sub tree reference node.");
                }

                IComposite parentComposite = referenceNode.ParentTask as IComposite;
                if (parentComposite == null)
                {
                    throw new Exception("Found task which has no parent composite.");
                }

                // Resolve reference.
                ITask treeReference = this.SolveReference(subTreeReference);

                // Remove from parent.
                parentComposite.RemoveChild(referenceNode.Task);

                // Add tree reference to parent at same position.
                parentComposite.InsertChild(referenceNode.Index, treeReference);
            }

            return(tree);
        }