//-----------------------------------------------------------------------------------------------
// GetPage
//
// Updates the page handle with the page with the given pageID
//-----------------------------------------------------------------------------------------------
t_rc STORM_FileHandle::GetPage(int pageID, STORM_PageHandle &pageHandle)
{
	STORM_Frame *pFrame;
	t_rc rc;

	if (!m_isOpened)
		return (STORM_FILENOTOPENED);

	// Check if page is not valid.
	if (pageID < 1)
		return (STORM_INVALIDPAGE);
		
	if (pageID > m_fileSubHeader.numAllocatedPages)
		return (STORM_INVALIDPAGE); 
		
	if (!IsPageReserved(pageID)) 
		return (STORM_INVALIDPAGE);

	rc = m_pBfrMgr->NeedPage(m_fileID, pageID, &pFrame);
	if (rc != OK) return (rc);

	rc = pageHandle.Open(pFrame);
	m_filePos = pageID;

	return (rc);
}
//-----------------------------------------------------------------------------------------------
// ReservePage
//
// Reserves a new page for the file.
//-----------------------------------------------------------------------------------------------
t_rc STORM_FileHandle::ReservePage(STORM_PageHandle &pageHandle)
{
	if (!m_isOpened)
		return (STORM_FILENOTOPENED);

	t_rc rc;
	int newPageID = INVALID_PAGEID; 

	for (int pageCounter=1; pageCounter<=MAX_PAGES_PER_FILE; pageCounter++)
	{
		if (!IsPageReserved(pageCounter))
		{
			newPageID = pageCounter;
			break;
		}
	}

	STORM_Frame *pFrame;

	if (newPageID == INVALID_PAGEID)  // all pages are reserved
	{
		if (m_fileSubHeader.numAllocatedPages == MAX_PAGES_PER_FILE)
			return STORM_FILELIMITREACHED;

		// Reserve frame in buffer.
		rc = m_pBfrMgr->ReserveFrame(m_fileID, newPageID, &pFrame);
		if (rc != OK) return (rc);
		m_fileSubHeader.numAllocatedPages++;
		m_fileSubHeader.numReservedPages++;
		UpdateHeaderFrame();

		rc = m_pBfrMgr->WritePage(pFrame);
		if (rc != OK) return (rc);
	}
	else  // a free page has been found
	{
		// Reserve frame in buffer.
		rc = m_pBfrMgr->ReserveFrame(m_fileID, newPageID, &pFrame);
		if (rc != OK) return (rc);
		m_fileSubHeader.numReservedPages++;
		UpdateHeaderFrame();

		if (newPageID > m_fileSubHeader.numAllocatedPages)
		{
			rc = m_pBfrMgr->WritePage(pFrame);
			if (rc != OK) return (rc);
			m_fileSubHeader.numAllocatedPages++;
			UpdateHeaderFrame();
		}
	}

	SetPageReservationFlag(newPageID, true);  // page is reserved now

	rc = pageHandle.Open(pFrame);
	if (rc != OK) return (rc);

	return (OK);
}