#include <windows.h>
#include <tchar.h>
#include "resource.h"
#include "myapp.h"
#include "myappwin.h"

extern mylib::CMyApp* g_pApp;

namespace mylib
{
CMyApp::CMyApp(HINSTANCE hInstance, HINSTANCE hPrevInstance)
{
	// Save the instance handle
	m_hInstance = hInstance;

	// Load the strings
	int nChar;
	nChar = LoadString(hInstance, IDS_MY_APPTITLE, m_szAppTitle, MAX_LOAD_STRING);
	m_szAppTitle[nChar] = 0;

	// Register the Window Class
	if(hPrevInstance == 0)
		CMyWin::Register(hInstance);
	ParseCommandLine();
}

CMyApp::~CMyApp()
{
}

int
CMyApp::Run(int nCmdShow)
{
	// Create Window
	CMyAppWin appwin(m_szAppTitle);

	// Create the document
	if(m_DocName.size() > 0)
	{
		std::vector<TCHAR>::const_iterator p = m_DocName.begin();
		m_doc = CMyPlain(&*p);
	}
	appwin.Show(nCmdShow);
	appwin.Update();

	POINT pt;
	pt.x = 0;
	pt.y = 0;
	HDC hdc = appwin.GetDC();
	SIZE sz = m_doc.Size(hdc);
	appwin.ReleaseDC(hdc);
	appwin.SetDrawSize(pt, sz);
	
	// Enter Message Loop
	MSG msg;
	while(GetMessage(&msg, 0, 0, 0))
	{
		TranslateMessage(&msg);
		DispatchMessage(&msg);
	}
	return (int)msg.wParam;
}

BOOL
CMyApp::ParseCommandLine()
{
	const TCHAR* pCmdLine = GetCommandLine();
	if(pCmdLine == 0)
		return FALSE;

	// First argument (executable name)
	const TCHAR* p = pCmdLine;
	while(*p <= (TCHAR)' ')
	{
		if(*p == 0)
			return FALSE;
		++p;
	}
	TCHAR q = ' ';
	if((*p == '"') || (*p == '\''))
	{
		q = *p;
		++p;
	}
	while(*p != q)
	{
		if(*p == 0)
			return FALSE;
		++p;
	}
	++p;
	// Second argument
	while(*p <= (TCHAR)' ')
	{
		if(*p == 0)
			return FALSE;
		++p;
	}
	if((*p == '"') || (*p == '\''))
	{
		q = *p;
		++p;
	}
	std::vector<TCHAR> arg;
	while(*p != q)
	{
		if(*p == 0)
		{
			arg.push_back((TCHAR)0);
			m_DocName = arg;
			return TRUE;
		}
		arg.push_back(*p);
		++p;
	}
	arg.push_back((TCHAR)0);
	m_DocName = arg;
	return TRUE;
}

}	// namespace mylib
