void CTemplateSelectDialog::Refresh()
{
	// Try refreshing the template files.
	bool changed = g_wwhizTemplateManager->Refresh();

	// Delete all the items in the tree.
	m_tree.DeleteAllItems();

	// Get the root tree item.
	CTreeCursor rootCursor = m_tree.GetRootItem();

	// Walk each template file.
	int count = g_wwhizTemplateManager->GetCount();
	for (int i = 0; i < count; i++)
	{
		// Add each template file to the root of the tree.
		WWhizTemplateGroup* file = g_wwhizTemplateManager->GetTemplateGroup(i);
		if (!file->IsActive())
			continue;
		CTreeCursor topCursor = rootCursor.AddTail(file->GetName());
		topCursor.SetData(NULL);

		// Add each template stored in the template file as children.
		for (int index = 0; index < file->GetCount(); index++)
		{
			WWhizTemplate* code = file->Get(index);
			if (code->GetName().GetAt(0) != '-')		// - is private.
				AddTreeItem(topCursor, (UINT)code, code->GetName());
			topCursor.SortChildren();
		}
	}

	// Sort the root.
	rootCursor.SortChildren();

	// Set the input focus to the tree.
	m_tree.SetFocus();
	m_tree.GetRootItem().Select();

	// If there wasn't a refresh, then check the tree state.
	if (!changed)
		changed |= g_wwhizTemplateManager->RestoreTreeState(m_tree);
}
static void AddTreeItem(CTreeCursor cursor, UINT id, CString name)
{
	int curPos = 0;
	int nextPos;

	// Autoexpand.
	bool autoExpand = false;
	if (name[0] == '+')
	{
		curPos++;
		autoExpand = true;
	}

	while (true)
	{
		// See if there is a sub-tree.
		nextPos = name.Find('|', curPos);
		if (nextPos == -1)
			break;

		CString branchName = name.Mid(curPos, nextPos - curPos);
		curPos = nextPos + 1;
		cursor = AddTreeBranch(cursor, branchName);
		if (autoExpand)
			cursor.GetParent().Expand();

		cursor.SortChildren();
	}

	CTreeCursor lastBranchCursor;
	lastBranchCursor = cursor.AddTail(name.Mid(curPos));
	lastBranchCursor.SetData(id);

	if (autoExpand)
	{
		lastBranchCursor.Expand();
		lastBranchCursor.GetParent().Expand();
	}

	cursor.SortChildren();
}