#include <9pm/windows.h>
#include <9pm/u.h>
#include <9pm/libc.h>

BOOL WINAPI
CreateProcess(LPCWSTR lpApplicationName, LPWSTR lpCommandLine, LPSECURITY_ATTRIBUTES lpProcessAttributes,
	LPSECURITY_ATTRIBUTES lpThreadAttributes, BOOL bInheritHandles, DWORD dwCreationFlags,
	LPVOID lpEnvironment, LPCWSTR lpCurrentDirectory, LPSTARTUPINFOW lpStartupInfo,
	LPPROCESS_INFORMATION lpProcessInformation)
{
	char *app, *cmd, *cd;
	Rune *rp;
	char *env, *p;
	STARTUPINFOA si;
	int n;
	BOOL b;

	if(win_useunicode)
		return CreateProcessW(lpApplicationName, lpCommandLine, lpProcessAttributes,
			lpThreadAttributes, bInheritHandles, dwCreationFlags,
			lpEnvironment, lpCurrentDirectory, lpStartupInfo,
			lpProcessInformation);

	app = 0;
	if(lpApplicationName)
		app = win_wstr2utf(lpApplicationName);

	cmd = 0;
	if(lpApplicationName)
		cmd = win_wstr2utf(lpCommandLine);

	cd = 0;
	if(lpCurrentDirectory)
		cd = win_wstr2utf(lpCurrentDirectory);

	memcpy(&si, lpStartupInfo, sizeof(si));
	if(lpStartupInfo->lpDesktop)
		si.lpDesktop = win_wstr2utf(lpStartupInfo->lpDesktop);
	if(lpStartupInfo->lpTitle)
		si.lpTitle = win_wstr2utf(lpStartupInfo->lpTitle);
	if(lpEnvironment) {
		for(rp=lpEnvironment,n=0; !(rp[0]==0 && rp[1]==0); rp++)
			n += runelen(*rp);
		n+=2;
		env = win_malloc(n);
		for(rp=lpEnvironment,p=env; !(rp[0]==0 && rp[1]==0); rp++)
			p += runetochar(p, rp);
		*p++ = 0;
		*p++ = 0;
	} else
		env = 0;

	b = CreateProcessA(app, cmd, lpProcessAttributes,
			lpThreadAttributes, bInheritHandles, dwCreationFlags,
			env, cd, &si,
			lpProcessInformation);
	win_free(env);
	win_free(cmd);
	win_free(app);
	win_free(cd);
	win_free(si.lpDesktop);
	win_free(si.lpTitle);
	return b;
}
