CDocument* CMyDocManager::OpenDocumentFile(LPCTSTR lpszFileName)
{
	// From MFC: CDocManager::OpenDocumentFile

	CString strFileName = lpszFileName;

	strFileName.TrimLeft();
	strFileName.TrimRight();
	if (strFileName[0] == '\"')
		strFileName.Delete(0);
	int nPos = strFileName.ReverseFind('\"');
	if (nPos != -1)
		strFileName.Delete(nPos);

	CString strQuery, strPage;
	nPos = strFileName.Find('?');
	if (nPos != -1)
	{
		strQuery = strFileName.Mid(nPos + 1);
		strFileName = strFileName.Left(nPos);
	}

	bool bPathTooLong = false;
	TCHAR szPath[_MAX_PATH];
	if (!AfxFullPath(szPath, strFileName))
		bPathTooLong = true;

	if (bPathTooLong || !PathFileExists(szPath))
	{
		// Try extracting page number
		nPos = strFileName.ReverseFind('#');
		if (nPos != -1)
		{
			strPage = strFileName.Mid(nPos + 1);
			strFileName = strFileName.Left(nPos);

			if (!AfxFullPath(szPath, strFileName))
				bPathTooLong = true;
		}
	}

	if (bPathTooLong)
	{
		AfxMessageBox(FormatString(IDS_PATH_TOO_LONG, szPath), MB_ICONEXCLAMATION | MB_OK);
		return NULL;
	}

	TCHAR szLinkName[_MAX_PATH];
	if (AfxResolveShortcut(GetMainWnd(), szPath, szLinkName, _MAX_PATH))
		lstrcpy(szPath, szLinkName);

	// find the highest confidence
	CDocTemplate::Confidence bestMatch = CDocTemplate::noAttempt;
	CDocTemplate* pBestTemplate = NULL;
	CDocument* pOpenDocument = NULL;
	CMainFrame* pOldMainFrm = (CMainFrame*) theApp.m_pMainWnd;

	POSITION pos = m_templateList.GetHeadPosition();
	while (pos != NULL)
	{
		CDocTemplate* pTemplate = (CDocTemplate*)m_templateList.GetNext(pos);
		ASSERT_KINDOF(CDocTemplate, pTemplate);

		CDocTemplate::Confidence match;
		ASSERT(pOpenDocument == NULL);
		match = pTemplate->MatchDocType(szPath, pOpenDocument);
		if (match > bestMatch)
		{
			bestMatch = match;
			pBestTemplate = pTemplate;
		}
		if (match == CDocTemplate::yesAlreadyOpen)
			break;
	}

	if (pOpenDocument != NULL)
	{
		POSITION pos = pOpenDocument->GetFirstViewPosition();
		if (pos != NULL)
		{
			CView* pView = pOpenDocument->GetNextView(pos);
			ASSERT_VALID(pView);

			CMainFrame* pMainFrm = (CMainFrame*) pView->GetTopLevelFrame();
			pMainFrm->ActivateDocument(pOpenDocument);
		}
		else
			TRACE(_T("Error: Can not find a view for document to activate.\n"));
	}

	if (pOpenDocument == NULL)
	{
		if (pBestTemplate == NULL)
		{
			AfxMessageBox(AFX_IDP_FAILED_TO_OPEN_DOC);
			return NULL;
		}

		pOpenDocument = pBestTemplate->OpenDocumentFile(szPath);
	}

	if (pOpenDocument != NULL)
	{
		CDjVuDoc* pDoc = (CDjVuDoc*) pOpenDocument;
		CDjVuView* pView = pDoc->GetDjVuView();
		CMainFrame* pMainFrm = pView->GetMainFrame();

		// CDocManager::OnDDECommand shows the previous main window.
		// If it was in the fullscreen mode, hide it back.
		if (pOldMainFrm != NULL && pOldMainFrm != pMainFrm && pOldMainFrm->IsFullscreenMode())
			pOldMainFrm->ShowWindow(SW_HIDE);

		if (!strPage.IsEmpty())
			pView->GoToURL(MakeUTF8String(_T("#") + strPage));
	}

	return pOpenDocument;
}