#Include Once "windows.bi"

Declare function ReadEngineInfo()As String
Declare Sub WriteEngineInfo(s As string)

Dim As STARTUPINFO si
Dim As PROCESS_INFORMATION pi
Dim As SECURITY_ATTRIBUTES sa
Dim As HANDLE hReadChildPipe,hWriteChildPipe
Dim Shared As HANDLE hReadPipe,hWritePipe

sa.nLength = Len(sa)
sa.lpSecurityDescriptor = NULL
sa.bInheritHandle = TRUE

If CreatePipe(@hReadChildPipe,@hWritePipe,@sa,0) = 0 Then
	MessageBox(0,"Ошибка создания пайпа 1","",MB_ICONERROR)
EndIf

If SetHandleInformation(hWritePipe,HANDLE_FLAG_INHERIT,0) = 0 Then
	MessageBox(0,"Ошибка установки права не наследования дескрипторов для 1 пайпа","",MB_ICONERROR)
EndIf

If CreatePipe(@hReadPipe,@hWriteChildPipe,@sa,0) = 0 Then
	MessageBox(0,"Ошибка создания пайпа 2","",MB_ICONERROR)
EndIf

If SetHandleInformation(hReadPipe,HANDLE_FLAG_INHERIT,0) = 0 Then
	MessageBox(0,"Ошибка установки права не наследования дескрипторов для 2 пайпа","",MB_ICONERROR)
EndIf

GetStartupInfo(@si)
si.dwFlags = STARTF_USESTDHANDLES Or STARTF_USESHOWWINDOW
si.wShowWindow = SW_HIDE
si.hStdOutput  = hWriteChildPipe
si.hStdError   = hWriteChildPipe
si.hStdInput   = hReadChildPipe

If CreateProcess(0,"Fruit-2-3-1.exe",0,0,TRUE,0,0,0,@si,@pi) = 0 Then
	MessageBox(0,"Ошибка создания дочернего процесса","",MB_ICONERROR)
EndIf
CloseHandle(hWriteChildPipe)
CloseHandle(hReadChildPipe)

Function ReadEngineInfo() As String
	Dim As Integer iTotalBytesAvail,iNumberOfBytesWritten
	Dim As String sRet,sBuf
	sBuf=Space(10000)
	PeekNamedPipe(hReadPipe,NULL,NULL,NULL,@iTotalBytesAvail,NULL)
	If iTotalBytesAvail>0 Then
		While iTotalBytesAvail>0
			iTotalBytesAvail=IIf(iTotalBytesAvail>10000,10000,iTotalBytesAvail)
			ReadFile(hReadPipe,StrPtr(sBuf),iTotalBytesAvail,@iNumberOfBytesWritten,NULL)
			Var i = InStr(Left(sBuf,iNumberOfBytesWritten),"bestmove")
			If i<>0 Then
				sRet = Mid(sBuf,i+9,5)
			EndIf
			PeekNamedPipe(hReadPipe,NULL,NULL,NULL,@iTotalBytesAvail,NULL)
		Wend
		If sRet = "" Then sRet = ReadEngineInfo()
		Return sRet
	Else
		Return "err"
	End If
End Function

Sub WriteEngineInfo(s As String)
	Dim As Integer iNumberOfBytesWritten
	Dim As String sBuf = s+ Chr(10)
	WriteFile(hWritePipe,StrPtr(sBuf),Len(sBuf),@iNumberOfBytesWritten,NULL)
	Sleep 1500
End Sub
