BOOL CXTPTabPaintManager::_CreateMultiRowIndexerBestFit(CXTPTabManager* pTabManager, int nWidth, int nRow, int nTotalLength)
{
	const int nRowCount = pTabManager->GetRowCount();
	const int nLengthPerRow = !m_bMultiRowJustified ? nWidth : min(nTotalLength / (nRowCount - nRow), nWidth);

	CXTPTabManager::ROW_ITEMS* pRowItems = pTabManager->m_pRowIndexer->GetRowItems();
	int x = 0;

	for (int i = pRowItems[nRow].nLastItem; i < pTabManager->GetItemCount(); i++)
	{
		CXTPTabManagerItem* pItem = pTabManager->GetItem(i);
		int nLength = pItem->GetButtonLength();

		if (x + nLength > nLengthPerRow && x != 0 && nLength > 0)
		{
			if (nRow == nRowCount - 1)
				return FALSE;

			pRowItems[nRow + 1].nFirstItem = pRowItems[nRow + 1].nLastItem = i;

			if (_CreateMultiRowIndexerBestFit(pTabManager, nWidth, nRow + 1, nTotalLength - x))
				return TRUE;

			if (x + nLength > nWidth)
				return FALSE;
		}
		pRowItems[nRow].nLastItem = i;
		pItem->m_nItemRow = nRow;
		x += nLength;
	}
	return TRUE;
}