bool XAP_App::saveState(bool bQuit)
{
	// gather the state data for platform code to deal with
	XAP_StateData sd;

	bool bRet = true;

	// We will store data for up to XAP_SD_MAX_FILES, making sure we save it for the last
	// focussed frame in the first slot

	XAP_Frame * pLastFrame = getLastFocussedFrame();

	UT_sint32 i;
	UT_sint32 j;
	
	for(i = 0, j = 0; i < m_vecFrames.getItemCount(); ++i, ++j)
	{
		XAP_Frame * pFrame = NULL;

		if(i == 0)
			pFrame = pLastFrame;
		else
			pFrame = m_vecFrames[i];

		if(pLastFrame == pFrame && j != 0)
		{
			// we have done this frame, but need to do the one at pos 0 in its place
			pFrame = m_vecFrames[0];
		}
		

		if(!pFrame)
		{
			--j;
			continue;
		}
		
		AD_Document * pDoc = pFrame->getCurrentDoc();

		if(!pDoc)
		{
			--j;
			continue;
		}

		UT_Error e = UT_OK;
		
		if(pDoc->isDirty())
		{
			// need to decide what to do about dirty documents; perhaps we should keep a
			// copy of the unsaved state under a different name?
			// for now just save (otherwise the user will loose the changes when app
			// hibernates)
			e = pDoc->save();
			if(e == UT_SAVE_NAMEERROR)
			{
				// this is an Untitled document
				UT_UTF8String s = pFrame->getNonDecoratedTitle();
				s += HIBERNATED_EXT;
				e = pDoc->saveAs(s.utf8_str(), 0);
			}
			
			bRet &= (UT_OK == e);
		}

		if(j >= XAP_SD_MAX_FILES || e != UT_OK)
		{
			// no storage space left -- nothing more we can do with this document, so move
			// to the next one (do not break, we need to deal with anything that is not
			// saved)
			
			--j;      // we want to preserve the j value 
			continue;
		}
		
			
		const char * file = pDoc->getFilename();
		if(file && strlen(file) < XAP_SD_FILENAME_LENGTH)
		{
			strncpy(sd.filenames[j], file, XAP_SD_FILENAME_LENGTH);

			AV_View * pView = pFrame->getCurrentView();
			if(pView)
			{
				sd.iDocPos[j]  = pView->getPoint();
				sd.iXScroll[j] = pView->getXScrollOffset();
				sd.iYScroll[j] = pView->getYScrollOffset();
			}
		}
		else
		{
			--j;
			continue;
		}
	}

	sd.iFileCount = j;
	
	if(!_saveState(sd))
		return false;

	if(bQuit)
	{
		// we have dealt with unsaved docs above, so just clean up any modeless dlgs and quit
		closeModelessDlgs();
		reallyExit();
	}

	return bRet;
}