#define	STRICT
#include	<windows.h>
#include	<commctrl.h>
#include	<tchar.h>
#include	"kctrl.h"
#include	"appmain.h"
#include	"fepbox.h"

DWORD	AppVersion = 22 ;
DWORD	DllVersion = 0 ;
#define	MAX_ARGV	10
DWORD	Argc = 0 ;
LPTSTR	Argv[ MAX_ARGV ] ;
BOOL	Quote[ MAX_ARGV ] ;

int WINAPI
#ifdef	_WIN32_WCE
WinMain( HINSTANCE hThisInst, HINSTANCE hPrevInst,
		 LPTSTR lpszArgs, int nWinMode )
#else	/* _WIN32_WCE */
WinMain( HINSTANCE hThisInst, HINSTANCE hPrevInst,
		 LPSTR lpszArgs, int nWinMode )
#endif	/* _WIN32_WCE */
{
	TCHAR	ch = 0 ;
	HWND	hWndParent = 0, hWnd ;

	_tcscpy( MessageBuf, (LPCTSTR) lpszArgs ) ;
	cmdline2args( MessageBuf, &Argc, Argv, Quote, NULL ) ;
	if ( Argc > 1 ) {
		hWndParent = (HWND) _ttol( Argv[ 1 ] ) ;
		if ( Argc > 2 ) {
			ch = (TCHAR) _ttol( Argv[ 2 ] ) ;
		}
	}

	/* 既に起動されているかどうかチェックする */
	hWnd = FindWindow( szTitleName, NULL ) ;
	if ( hWnd != NULL ) {
		/* 起動済みの方をアクティブにする */
		if ( hWndParent ) {
			PostMessage( hWnd, WM_COMMAND, MAKEWPARAM( IDM_ACTIVATE_HWND, ch ), (LPARAM) hWndParent ) ;
		} else {
			hWndParent = GetCenterWindow() ;
			SendMessage( hWnd, WM_COMMAND, IDM_ACTIVATE, (LPARAM) hWndParent ) ;
		}
		return TRUE ;
	}

#ifdef	_WIN32_WCE
	InitCommonControls() ;
#endif	/* _WIN32_WCE */

	/* KCTRL.DLLの初期化を行う */
	if ( !InitKanjiControls() ) {
		wsprintf( MessageBuf, TEXT("KCTRL.DLL Initialize error\r\nError=%x"),
				  GetLastError() ) ;
		MessageBeep( MB_ICONEXCLAMATION ) ;
		MessageBox( NULL, MessageBuf, TEXT("KCTRL Error"), MB_OK ) ;
		return -1 ;
	}
	DllVersion = GetKVersion() ;

	BOOL		exitVal = FALSE ;
	MainApp		*pApp = new MainApp() ;
	if ( !pApp ) {
		goto exit ;
	}
	if ( pApp->Create( hThisInst, hWndParent, ch ) ) {
		exitVal = pApp->Run() ;
	}
	delete pApp ;

exit:
	ReleaseKanjiControls() ;
	return exitVal ;
}

/*
 * コマンドライン関係
 */
void
cmdline2args( LPTSTR cmdline, LPDWORD argc, LPTSTR *argv, LPBOOL quote, LPTSTR args )
{
	TCHAR	c ;
	BOOL	f_skip = TRUE, f_quote = FALSE ;

	if ( args ) {
		*args = 0 ;
	}
	argv[ 0 ] = TEXT("") ;
	quote[ 0 ] = FALSE ;
	*argc = 1 ;
	while ( c = *cmdline ) {
		if ( f_skip ) {
			if ( !(c == TEXT(' ') || c == TEXT('\t')) ) {
				if ( args && *argc == 2 ) {
					_tcscpy( args, cmdline ) ;
				}
				if ( c == TEXT('"') ) {
					f_quote = TRUE ;
					cmdline ++ ;
				}
				quote[ (*argc) ] = f_quote ;
				argv[ (*argc) ++ ] = cmdline ;
				f_skip = FALSE ;
			}
		} else {
			if ( f_quote ) {
				if ( c == TEXT('"') ) {
					f_quote = FALSE ;
					*cmdline = 0 ;
					f_skip = TRUE ;
				}
			} else if ( (c == TEXT(' ') || c == TEXT('\t')) ) {
				*cmdline = 0 ;
				f_skip = TRUE ;
			}
		}
		cmdline ++ ;
	}
}
