Connect WB cores command to UCI option Threads
[uci2wb.git] / UCI2WB.c
1 /************************* UCI2WB by H.G.Muller ****************************/\r
2 \r
3 #define VERSION "1.10"\r
4 \r
5 #include <stdio.h>\r
6 #include <stdlib.h>\r
7 #ifdef WIN32\r
8 #  include <windows.h>\r
9 #  include <io.h>\r
10    HANDLE process;\r
11    DWORD thread_id;\r
12 #else\r
13 #  include <pthread.h>\r
14 #  include <signal.h>\r
15 #  define NO_ERROR 0\r
16 #  include <sys/time.h>\r
17    int GetTickCount() // with thanks to Tord\r
18    { struct timeval t; gettimeofday(&t, NULL); return t.tv_sec*1000 + t.tv_usec/1000; }\r
19 #endif\r
20 #include <fcntl.h>\r
21 #include <string.h>\r
22 \r
23 // Set VARIANTS for in WinBoard variant feature. (With -s option this will always be reset to use "shogi".)\r
24 #  define VARIANTS "normal,xiangqi"\r
25 \r
26 #define DPRINT if(debug) printf\r
27 \r
28 #define WHITE 0\r
29 #define BLACK 1\r
30 #define NONE  2\r
31 #define ANALYZE 3\r
32 \r
33 char move[2000][10], checkOptions[8192], iniPos[256], hashOpt[20], pause, pondering, suspended, ponder, post, hasHash, c, sc='c', *suffix, *variants;\r
34 int mps, tc, inc, sTime, depth, myTime, hisTime, stm, computer = NONE, memory, oldMem=0, cores, moveNr, lastDepth, lastScore, startTime, debug;\r
35 int statDepth, statScore, statNodes, statTime, currNr, size, collect, nr, sm, inex, on[500];\r
36 char currMove[20], moveMap[500][10], /* for analyze mode */ canPonder[20], threadOpt[20];\r
37 \r
38 FILE *toE, *fromE, *fromF;\r
39 int pid;\r
40 \r
41 #ifdef WIN32\r
42 WinPipe(HANDLE *hRd, HANDLE *hWr)\r
43 {\r
44   SECURITY_ATTRIBUTES saAttr;\r
45 \r
46   /* Set the bInheritHandle flag so pipe handles are inherited. */\r
47   saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);\r
48   saAttr.bInheritHandle = TRUE;\r
49   saAttr.lpSecurityDescriptor = NULL;\r
50 \r
51   /* Create a pipe */\r
52   return CreatePipe(hRd, hWr, &saAttr, 0);\r
53 }\r
54 #endif\r
55 \r
56 #define INIT 0\r
57 #define WAKEUP 1\r
58 #define PAUSE 2\r
59 \r
60 void\r
61 Sync (int action)\r
62 {\r
63 #ifdef WIN32\r
64         static HANDLE hWr, hRd; DWORD d; char c;\r
65         switch(action) {\r
66             case INIT:   WinPipe(&hRd, &hWr); break;\r
67             case WAKEUP: WriteFile(hWr, "\n", 1, &d, NULL); break;\r
68             case PAUSE:  ReadFile(hRd, &c, 1, &d, NULL);\r
69         }\r
70 #else\r
71         static int syncPipe[2]; char c;\r
72         switch(action) {\r
73             case INIT:   pipe(syncPipe); break;\r
74             case WAKEUP: write(syncPipe[1], "\n", 1); break;\r
75             case PAUSE:  read(syncPipe[0], &c, 1);\r
76         }\r
77 #endif\r
78 }\r
79 \r
80 void\r
81 StartSearch(char *ponder)\r
82 {       // send the 'go' command to engine. Suffix by ponder.\r
83         int x = (ponder[0] != 0);\r
84         int nr = moveNr + x; // we ponder for one move ahead!\r
85         fprintf(toE, "\ngo btime %d wtime %d", stm == BLACK ^ x ^ sc=='s' ? myTime : hisTime, stm == WHITE ^ x ^ sc=='s' ? myTime : hisTime);\r
86         DPRINT(    "\n# go btime %d wtime %d", stm == BLACK ^ x ^ sc=='s' ? myTime : hisTime, stm == WHITE ^ x ^ sc=='s' ? myTime : hisTime);\r
87         if(sTime > 0) { fprintf(toE, " movetime %d", sTime); DPRINT(" movetime %d", sTime); } else\r
88         if(mps) { fprintf(toE, " movestogo %d", mps*(nr/(2*mps)+1)-nr/2); DPRINT(" movestogo %d", mps*(nr/(2*mps)+1)-nr/2); }\r
89         if(inc && !suffix) { fprintf(toE, " winc %d binc %d", inc, inc); DPRINT(" winc %d binc %d", inc, inc); }\r
90         if(depth > 0) { fprintf(toE, " depth %d", depth); DPRINT(" depth %d", depth); }\r
91         if(suffix) { fprintf(toE, suffix, inc); DPRINT(suffix, inc); }\r
92         fprintf(toE, "%s\n", ponder);\r
93         DPRINT("%s\n", ponder);\r
94 }\r
95 \r
96 void\r
97 StopPonder(int pondering)\r
98 {\r
99         if(!pondering) return;\r
100         pause = 1;\r
101         fprintf(toE, "stop\n"); fflush(toE); DPRINT("# stop\n"); // note: 'pondering' remains set until engine acknowledges 'stop' with 'bestmove'\r
102         Sync(PAUSE); // wait for engine to acknowledge 'stop' with 'bestmove'.\r
103 }\r
104 \r
105 void\r
106 LoadPos(int moveNr)\r
107 {\r
108         int j;\r
109         fprintf(toE, "%s moves", iniPos);\r
110         DPRINT(    "# %s moves", iniPos);\r
111         for(j=0; j<moveNr; j++) { fprintf(toE, " %s", move[j]); DPRINT(" %s", move[j]); }\r
112 }\r
113 \r
114 void\r
115 StartPonder()\r
116 {\r
117         if(!move[moveNr][0]) return; // no ponder move\r
118         LoadPos(moveNr+1);\r
119         pondering = 1; lastDepth = 1;\r
120         StartSearch(" ponder");\r
121 }\r
122 \r
123 char *Convert(char *pv)\r
124 {   // convert Shogi coordinates to WB\r
125     char *p, *q, c;\r
126     static char buf[10000];\r
127     if(sc != 's') return pv;\r
128     p = pv; q = buf;\r
129     while(c = *p++) {\r
130         if(c >= '0' && c <= '9' || c >= 'a' && c <= 'z') *q++ = 'a'+'0'+size - c; else *q++ = c;\r
131     }\r
132     *q++ = 0;\r
133     return buf;\r
134 }\r
135 \r
136 void\r
137 Move4GUI(char *m)\r
138 {\r
139     if(sc == 's') {\r
140       // convert USI move to WB format\r
141       m[2] = 'a'+'0'+size - m[2];\r
142       m[3] = 'a'+'0'+size - m[3];\r
143       if(m[1] == '*') { // drop\r
144         m[1] = '@';\r
145       } else {\r
146         m[0] = 'a'+'0'+size - m[0];\r
147         m[1] = 'a'+'0'+size - m[1];\r
148         if((stm == WHITE ? (m[1]>'0'+size-size/3 || m[3]>'0'+size-size/3)\r
149                                 : (m[1] <= '0'+size/3 || m[3] <= '0'+size/3)) && m[4] != '+')\r
150              m[4] = '=', m[5] = 0;\r
151       }\r
152     }\r
153 }\r
154 \r
155 int\r
156 GetChar()\r
157 {\r
158     int c;\r
159     if(fromF) {\r
160         if((c = fgetc(fromF)) != EOF) return c;\r
161         fclose(fromF); fromF = 0; printf("# end fake\n");\r
162     }\r
163     return fgetc(fromE);\r
164 }\r
165 \r
166 void *\r
167 Engine2GUI()\r
168 {\r
169     char line[1024], command[256];\r
170 \r
171     if(fromF = fopen("DefectiveEngineOptions.ini", "r")) printf("# fake engine input\n");\r
172     while(1) {\r
173         int i=0, x; char *p, dummy;\r
174 \r
175         fflush(stdout); fflush(toE);\r
176         while((line[i] = x = GetChar()) != EOF && line[i] != '\n') i++;\r
177         line[++i] = 0;\r
178         if(x == EOF) exit(0);\r
179         DPRINT("# engine said: %s", line), fflush(stdout);\r
180         if(sscanf(line, "%s", command) != 1) continue;\r
181         if(!strcmp(command, "bestmove")) {\r
182             if(pause) { pondering = pause = 0; Sync(WAKEUP); continue; } // bestmove was reply to ponder miss or analysis result; ignore.\r
183             // move was a move to be played\r
184             if(strstr(line+9, "resign")) { printf("resign\n"); computer = NONE; }\r
185             if(strstr(line+9, "(none)") || strstr(line+9, "null") ||\r
186                strstr(line+9, "0000")) { printf("%s\n", lastScore < -99999 ? "resign" : "1/2-1/2 {stalemate}"); computer = NONE; }\r
187             sscanf(line, "bestmove %s", move[moveNr++]);\r
188             myTime -= (GetTickCount() - startTime)*1.02 + inc; // update own clock, so we can give correct wtime, btime with ponder\r
189             if(mps && ((moveNr+1)/2) % mps == 0) myTime += tc; if(sTime) myTime = sTime; // new session or move starts\r
190             stm = WHITE+BLACK - stm;\r
191             // first start a new ponder search, if pondering is on and we have a move to ponder on\r
192             if(p = strstr(line+9, "ponder")) {\r
193               sscanf(p+7, "%s", move[moveNr]);\r
194               if(computer != NONE && ponder) {\r
195                 DPRINT("# ponder on %s\n", move[moveNr]);\r
196                 StartPonder();\r
197               }\r
198               p[-1] = '\n'; *p = 0; // strip off ponder move\r
199             } else move[moveNr][0] = 0;\r
200             Move4GUI(line+9);\r
201             printf("move %s\n", line+9); // send move to GUI\r
202             if(lastScore == 100001 && iniPos[0] != 'f') { printf("%s {mate}\n", stm == BLACK ? "1-0" : "0-1"); computer = NONE; }\r
203         }\r
204         else if(!strcmp(command, "info")) {\r
205             int d=0, s=0, t=0, n=0;\r
206             char *pv;\r
207             if(sscanf(line+5, "string times @ %c", &dummy) == 1) { printf("# %s", line+12); continue; }\r
208             if(collect && (pv = strstr(line+5, "currmove "))) {\r
209                 if(p = strstr(line+5, "currmovenumber ")) {\r
210                     n = atoi(p+15);\r
211                     if(collect == 1 && n != 1) continue; // wait for move 1\r
212                     if(collect + (n == 1) > 2) { // done collecting\r
213                         if(inex && collect == 2) printf("%d 0 0 0 OK to exclude\n", lastDepth);\r
214                         collect = 3; continue;\r
215                     }\r
216                     collect = 2; on[nr=n] = 1; sscanf(pv+9, "%s", moveMap[n]); continue; // store move\r
217                 }\r
218             }\r
219             if(!post) continue;\r
220             if(sscanf(line+5, "string %c", &dummy) == 1) printf("%d 0 0 0 %s", lastDepth, line+12); else {\r
221                 if(p = strstr(line+4, " depth "))      sscanf(p+7, "%d", &d), statDepth = d;\r
222                 if(p = strstr(line+4, " score cp "))   sscanf(p+10, "%d", &s), statScore = s; else\r
223                 if(p = strstr(line+4, " score mate ")) sscanf(p+12, "%d", &s), s += s>0 ? 100000 : -100000, statScore = s; else\r
224                 if(p = strstr(line+4, " score "))      sscanf(p+7, "%d", &s), statScore = s;\r
225                 if(p = strstr(line+4, " nodes "))      sscanf(p+7, "%d", &n), statNodes = n;\r
226                 if(p = strstr(line+4, " time "))       sscanf(p+6, "%d", &t), t /= 10, statTime = t;\r
227                 if(p = strstr(line+4, " currmove "))   sscanf(p+10,"%s", currMove);\r
228                 if(p = strstr(line+4, " currmovenumber ")) sscanf(p+16,"%d", &currNr);\r
229                 if(pv = strstr(line+4, " pv ")) // convert PV info to WB thinking output\r
230                     printf("%3d  %6d %6d %10d %s", lastDepth=d, lastScore=s, t, n, Convert(pv+4));\r
231             }\r
232         }\r
233         else if(!strcmp(command, "option")) { // USI option: extract data fields\r
234             char name[80], type[80], buf[1024], val[256], *q;\r
235             int min=0, max=1e9;\r
236             if(p = strstr(line+6, " type ")) sscanf(p+1, "type %s", type), *p = '\n';\r
237             if(p = strstr(line+6, " min "))  sscanf(p+1, "min %d", &min), *p = '\n';\r
238             if(p = strstr(line+6, " max "))  sscanf(p+1, "max %d", &max), *p = '\n';\r
239             if(p = strstr(line+6, " default "))  sscanf(p+1, "default %[^\n]*", val), *p = '\n';\r
240             if(p = strstr(line+6, " name ")) sscanf(p+1, "name %[^\n]*", name);\r
241             if(!strcmp(name, "Threads")) { strcpy(threadOpt, name); continue; }\r
242             if(!strcmp(name, "Ponder") || !strcmp(name, "USI_Ponder")) { strcpy(canPonder, name); continue; }\r
243             if(!strcmp(name, "Hash") || !strcmp(name, "USI_Hash")) {\r
244                 memory = oldMem = atoi(val); hasHash = 1; \r
245                 strcpy(hashOpt, name);\r
246                 continue;\r
247             }\r
248             // pass on engine-defined option as WB option feature\r
249             if(!strcmp(type, "filename")) type[4] = 0;\r
250             sprintf(buf, "feature option=\"%s -%s", name, type); q = buf + strlen(buf);\r
251             if(     !strcmp(type, "file")\r
252                  || !strcmp(type, "string")) sprintf(q, " %s\"\n", val);\r
253             else if(!strcmp(type, "spin"))   sprintf(q, " %d %d %d\"\n", atoi(val), min, max);\r
254             else if(!strcmp(type, "check"))  sprintf(q, " %d\"\n", strcmp(val, "true") ? 0 : 1), strcat(checkOptions, name);\r
255             else if(!strcmp(type, "button")) sprintf(q, "\"\n");\r
256             else if(!strcmp(type, "combo")) {\r
257                 if(p = strstr(line+6, " default "))  sscanf(p+1, "default %s", type); // current setting\r
258                 min = 0; p = line+6;\r
259                 while(p = strstr(p, " var ")) {\r
260                     sscanf(p += 5, "%s", val); // next choice\r
261                     sprintf(buf + strlen(buf), "%s%s%s", min++ ? " /// " : " ", strcmp(type, val) ? "" : "*", val);\r
262                 }\r
263                 strcat(q, "\"\n");\r
264             }\r
265             else buf[0] = 0; // ignore unrecognized option types\r
266             if(buf[0]) printf("%s", buf);\r
267         }\r
268         else if(!strcmp(command, "id")) {\r
269             char name[256];\r
270             if(sscanf(line, "id name %[^\n]", name) == 1) printf("feature myname=\"%s (U%cI2WB)\"\n", name, sc-32);\r
271         }\r
272         else if(!strcmp(command, "readyok")) { pause = 0; Sync(WAKEUP); } // resume processing of GUI commands\r
273         else if(sscanf(command, "u%ciok", &c)==1 && c==sc)   printf("feature smp=1 memory=%d done=1\n", hasHash), Sync(WAKEUP); // done with options\r
274     }\r
275 }\r
276 \r
277 void\r
278 Move4Engine(char *m)\r
279 {\r
280     if(sc == 's') {\r
281       // convert input move to USI format\r
282       if(m[1] == '@') { // drop\r
283         m[1] = '*';\r
284       } else {\r
285         m[0] = 'a'+'0'+size - m[0];\r
286         m[1] = 'a'+'0'+size - m[1];\r
287       }\r
288       m[2] = 'a'+'0'+size - m[2];\r
289       m[3] = 'a'+'0'+size - m[3];\r
290       if(m[4] == '=') m[4] = 0; // no '=' in USI format!\r
291       else if(m[4]) m[4] = '+'; // cater to WB 4.4 bug :-(\r
292     }\r
293 }\r
294 \r
295 void\r
296 GUI2Engine()\r
297 {\r
298     char line[256], command[256], *p, *q, *r;\r
299 \r
300     while(1) {\r
301         int i, x;\r
302 \r
303         if((computer == stm || computer == ANALYZE) && !suspended) {\r
304             DPRINT("# start search\n");\r
305             LoadPos(moveNr); // load position\r
306             // and set engine thinking (note USI swaps colors!)\r
307             startTime = GetTickCount();\r
308             if(computer == ANALYZE) {\r
309                 fprintf(toE, "\ngo infinite"); DPRINT("\n# go infinite");\r
310                 if(sm & 1) { // some moves are disabled\r
311                     fprintf(toE, " searchmoves"); DPRINT(" searchmoves");\r
312                     for(i=1; i<nr; i++) if(on[i]) { fprintf(toE, " %s", moveMap[i]); DPRINT(" %s", moveMap[i]); }\r
313                 }\r
314                 fprintf(toE, "\n"); DPRINT("\n");\r
315             // code for searchmoves goes here\r
316             } else StartSearch("");\r
317         }\r
318       nomove:\r
319         fflush(toE); fflush(stdout);\r
320         i = 0; while((x = getchar()) != EOF && (line[i] = x) != '\n') i++;\r
321         line[++i] = 0; if(x == EOF) { printf("# EOF\n"); exit(-1); }\r
322         sscanf(line, "%s", command);\r
323         if(!strcmp(command, "new")) {\r
324             computer = BLACK; moveNr = 0; depth = -1; move[0][0] = 0;\r
325             stm = WHITE; strcpy(iniPos, "position startpos");\r
326             if(memory != oldMem && hasHash) fprintf(toE, "setoption name %s value %d\n", hashOpt, memory);\r
327             oldMem = memory;\r
328             // we can set other options here\r
329             pause = 1; // wait for option settings to take effect\r
330             fprintf(toE, "isready\n");\r
331             fprintf(toE, "u%cinewgame\n", sc); fflush(toE);\r
332             Sync(PAUSE); // wait for readyok\r
333         }\r
334         else if(!strcmp(command, "usermove")) {\r
335             sscanf(line, "usermove %s", command); // strips off linefeed\r
336             Move4Engine(command);\r
337             stm = WHITE+BLACK - stm; collect = (computer == ANALYZE); sm = 0;\r
338             // when pondering we either continue the ponder search as normal search, or abort it\r
339             if(pondering || computer == ANALYZE) {\r
340                 if(pondering && !strcmp(command, move[moveNr])) { // ponder hit\r
341                     pondering = 0; moveNr++; startTime = GetTickCount(); // clock starts running now\r
342                     fprintf(toE, "ponderhit\n"); DPRINT("# ponderhit\n");\r
343                     goto nomove;\r
344                 }\r
345                 StopPonder(1);\r
346             }\r
347             strcpy(move[moveNr++], command); // possibly overwrites ponder move\r
348         }\r
349         else if(!strcmp(command, "level")) {\r
350             int sec = 0;\r
351             sscanf(line, "level %d %d:%d %d", &mps, &tc, &sec, &inc) == 4 ||\r
352             sscanf(line, "level %d %d %d", &mps, &tc, &inc);\r
353             tc = (60*tc + sec)*1000; inc *= 1000; sTime = 0;\r
354         }\r
355         else if(!strcmp(command, "option")) {\r
356             char name[80], *p;\r
357             if(sscanf(line+7, "UCI2WB debug output=%d", &debug) == 1) ; else\r
358             if(p = strchr(line, '=')) {\r
359                 *p++ = 0;\r
360                 if(strstr(checkOptions, line+7)) sprintf(p, "%s\n", atoi(p) ? "true" : "false");\r
361                 fprintf(toE, "setoption name %s value %s", line+7, p); DPRINT("# setoption name %s value %s", line+7, p);\r
362             } else { fprintf(toE, "setoption name %s\n", line+7); DPRINT("# setoption name %s\n", line+7); }\r
363         }\r
364         else if(!strcmp(command, "protover")) {\r
365             if(!variants) variants = sc=='s' ? "shogi,5x5+5_shogi" : VARIANTS;\r
366             printf("feature variants=\"%s\" setboard=1 usermove=1 debug=1 ping=1 reuse=0 exclude=1 pause=1 done=0\n", variants);\r
367             printf("feature option=\"UCI2WB debug output -check %d\"\n", debug);\r
368             fprintf(toE, "u%ci\n", sc); fflush(toE); // this prompts UCI engine for options\r
369             Sync(PAUSE); // wait for uciok\r
370         }\r
371         else if(!strcmp(command, "setboard")) {\r
372                 if(strstr(line+9, " b ")) stm = BLACK;\r
373                 if(p = strchr(line+9, '[')) { char c;\r
374                     *p++ = 0; q = strchr(p, ']'); *q = 0; r = q + 4; \r
375                     if(sc == 's') q[2] = 'w' + 'b' - q[2], strcpy(r=q+3, " 1\n"); // Shogi: reverse color\r
376                     else r = strchr(strchr(q+4, ' ') + 1, ' '); // skip to second space (after e.p. square)\r
377                     *r = 0; sprintf(command, "%s%s %s %s", line+9, q+1, p, r+1);\r
378                 } else strcpy(command, line+9);\r
379                 sprintf(iniPos, "%s%sfen %s", iniPos[0]=='p' ? "position " : "", sc=='s' ? "s" : "", command);\r
380                 iniPos[strlen(iniPos)-1] = sm = 0; collect = (computer == ANALYZE);\r
381         }\r
382         else if(!strcmp(command, "variant")) {\r
383                 if(!strcmp(line+8, "shogi\n")) size = 9, strcpy(iniPos, "position startpos");\r
384                 if(!strcmp(line+8, "5x5+5_shogi\n")) size = 5, strcpy(iniPos, "position startpos");\r
385                 if(!strcmp(line+8, "xiangqi\n")) strcpy(iniPos, "fen rnbakabnr/9/1c5c1/p1p1p1p1p/9/9/P1P1P1P1P/1C5C1/9/RNBAKABNR r");\r
386         }\r
387         else if(!strcmp(command, "undo") && (i=1) || !strcmp(command, "remove") && (i=2)) {\r
388             if(pondering || computer == ANALYZE) StopPonder(1);\r
389             moveNr = moveNr > i ? moveNr - i : 0; collect = (computer == ANALYZE); sm = 0;\r
390         }\r
391         else if(!strcmp(command, ".")) {\r
392             printf("stat01: %d %d %d %d 100 %s\n", statTime, statNodes, statDepth, 100-currNr, currMove);\r
393             goto nomove;\r
394         }\r
395         else if(!strcmp(command+2, "clude") && collect > 2) { // include or exclude\r
396             int all = !strcmp(line+8, "all"), in = command[1] == 'n';\r
397             inex = 1; line[strlen(line)-1] = sm = 0; // strip LF and clear sm flag\r
398             for(i=1; i<nr; i++) { if(!strcmp(line+8, moveMap[i]) || all) on[i] = in; sm |= on[i]+1; } // sm: 2 = enabled, 1 = disabled\r
399             if(!(sm & 2)) goto nomove; // no moves enabled; continue current search\r
400             if(computer == ANALYZE) StopPonder(1); // abort old analysis\r
401         }\r
402         else if(!strcmp(command, "pause")) {\r
403             if(computer == stm) myTime -= GetTickCount() - startTime;\r
404             suspended = 1 + pondering; // remember if we were pondering, and stop search ignoring bestmove\r
405             StopPonder(pondering || computer == stm);\r
406         }\r
407         else if(!strcmp(command, "resume")) {\r
408             if(suspended == 2) StartPonder(); // restart interrupted ponder search\r
409             suspended = 0; // causes thinking to start in normal way if on move or analyzing\r
410         }\r
411         else if(!strcmp(command, "xboard")) ;\r
412         else if(!strcmp(command, "analyze"))computer = ANALYZE, collect = 1, sm = 0;\r
413         else if(!strcmp(command, "exit"))   computer = NONE, StopPonder(1);\r
414         else if(!strcmp(command, "force"))  computer = NONE, StopPonder(pondering);\r
415         else if(!strcmp(command, "go"))     computer = stm;\r
416         else if(!strcmp(command, "time"))   sscanf(line+4, "%d", &myTime),  myTime  *= 10;\r
417         else if(!strcmp(command, "otim"))   sscanf(line+4, "%d", &hisTime), hisTime *= 10;\r
418         else if(!strcmp(command, "post"))   post = 1;\r
419         else if(!strcmp(command, "nopost")) post = 0;\r
420         else if(!strcmp(command, "easy") && !!*canPonder) ponder = 0, StopPonder(pondering), fprintf(toE, "setoption name %s value false\n", canPonder);\r
421         else if(!strcmp(command, "hard") && !!*canPonder) ponder = 1, fprintf(toE, "setoption name %s value true\n", canPonder), StartPonder();\r
422         else if(!strcmp(command, "ping"))   pause = 1, fprintf(toE, "isready\n"), fflush(toE), Sync(PAUSE), printf("pong %s", line+5);\r
423         else if(!strcmp(command, "memory")) sscanf(line, "memory %d", &memory);\r
424         else if(!strcmp(command, "cores")&& !!*threadOpt) sscanf(line, "cores %d", &cores), fprintf(toE, "setoption name %s value %d\n", threadOpt, cores);\r
425         else if(!strcmp(command, "sd"))     sscanf(line, "sd %d", &depth);\r
426         else if(!strcmp(command, "st"))     sscanf(line, "st %d", &sTime), sTime = 1000*sTime - 30, inc = 0;\r
427         else if(!strcmp(command, "quit"))   fprintf(toE, "quit\n"), fflush(toE), exit(0);\r
428     }\r
429 }\r
430 \r
431 int\r
432 StartEngine(char *cmdLine, char *dir)\r
433 {\r
434 #ifdef WIN32\r
435   HANDLE hChildStdinRd, hChildStdinWr,\r
436     hChildStdoutRd, hChildStdoutWr;\r
437   BOOL fSuccess;\r
438   PROCESS_INFORMATION piProcInfo;\r
439   STARTUPINFO siStartInfo;\r
440   DWORD err;\r
441 \r
442   /* Create a pipe for the child's STDOUT. */\r
443   if (! WinPipe(&hChildStdoutRd, &hChildStdoutWr)) return GetLastError();\r
444 \r
445   /* Create a pipe for the child's STDIN. */\r
446   if (! WinPipe(&hChildStdinRd, &hChildStdinWr)) return GetLastError();\r
447 \r
448   SetCurrentDirectory(dir); // go to engine directory\r
449 \r
450   /* Now create the child process. */\r
451   siStartInfo.cb = sizeof(STARTUPINFO);\r
452   siStartInfo.lpReserved = NULL;\r
453   siStartInfo.lpDesktop = NULL;\r
454   siStartInfo.lpTitle = NULL;\r
455   siStartInfo.dwFlags = STARTF_USESTDHANDLES;\r
456   siStartInfo.cbReserved2 = 0;\r
457   siStartInfo.lpReserved2 = NULL;\r
458   siStartInfo.hStdInput = hChildStdinRd;\r
459   siStartInfo.hStdOutput = hChildStdoutWr;\r
460   siStartInfo.hStdError = hChildStdoutWr;\r
461 \r
462   fSuccess = CreateProcess(NULL,\r
463                            cmdLine,        /* command line */\r
464                            NULL,           /* process security attributes */\r
465                            NULL,           /* primary thread security attrs */\r
466                            TRUE,           /* handles are inherited */\r
467                            DETACHED_PROCESS|CREATE_NEW_PROCESS_GROUP,\r
468                            NULL,           /* use parent's environment */\r
469                            NULL,\r
470                            &siStartInfo, /* STARTUPINFO pointer */\r
471                            &piProcInfo); /* receives PROCESS_INFORMATION */\r
472 \r
473   if (! fSuccess) return GetLastError();\r
474 \r
475 //  if (0) { // in the future we could trigger this by an argument\r
476 //    SetPriorityClass(piProcInfo.hProcess, GetWin32Priority(appData.niceEngines));\r
477 //  }\r
478 \r
479   /* Close the handles we don't need in the parent */\r
480   CloseHandle(piProcInfo.hThread);\r
481   CloseHandle(hChildStdinRd);\r
482   CloseHandle(hChildStdoutWr);\r
483 \r
484   process = piProcInfo.hProcess;\r
485   pid = piProcInfo.dwProcessId;\r
486   fromE = (FILE*) _fdopen( _open_osfhandle((long)hChildStdoutRd, _O_TEXT|_O_RDONLY), "r");\r
487   toE   = (FILE*) _fdopen( _open_osfhandle((long)hChildStdinWr, _O_WRONLY), "w");\r
488 #else\r
489     char *argv[10], *p, buf[200];\r
490     int i, toEngine[2], fromEngine[2];\r
491 \r
492     if (dir && dir[0] && chdir(dir)) { perror(dir); exit(1); }\r
493     pipe(toEngine); pipe(fromEngine); // create two pipes\r
494 \r
495     if ((pid = fork()) == 0) { // Child\r
496         dup2(toEngine[0], 0);   close(toEngine[0]);   close(toEngine[1]);   // stdin from toE pipe\r
497         dup2(fromEngine[1], 1); close(fromEngine[0]); close(fromEngine[1]); // stdout into fromE pipe\r
498         dup2(1, fileno(stderr)); // stderr into frome pipe\r
499 \r
500         strcpy(buf, cmdLine); p = buf;\r
501         for (i=0;;) { argv[i++] = p; p = strchr(p, ' '); if (p == NULL) break; *p++ = 0; }\r
502         argv[i] = NULL;\r
503         execvp(argv[0], argv); // startup engine\r
504         \r
505         perror(argv[0]); exit(1); // could not start engine; quit.\r
506     }\r
507     signal(SIGPIPE, SIG_IGN);\r
508     close(toEngine[0]); close(fromEngine[1]); // close engine ends of pipes in adapter\r
509     \r
510     fromE = (FILE*) fdopen(fromEngine[0], "r"); // make into high-level I/O\r
511     toE   = (FILE*) fdopen(toEngine[1], "w");\r
512 #endif\r
513   return NO_ERROR;\r
514 }\r
515 \r
516 main(int argc, char **argv)\r
517 {\r
518         char *dir = NULL, *p, *q; int e;\r
519 \r
520         if(argc == 2 && !strcmp(argv[1], "-v")) { printf("UCI2WB " VERSION " by H.G.Muller\n"); exit(0); }\r
521         if(argc > 1 && !strcmp(argv[1], "debug")) { debug = 1; argc--; argv++; }\r
522         if(argc > 1 && !strcmp(argv[1], "-var")) { variants = argv[2]; argc-=2; argv+=2; }\r
523         if(argc > 1 && argv[1][0] == '-') { sc = argv[1][1]; argc--; argv++; }\r
524         if(argc < 2) { printf("usage is: U%cI2WB [debug] [-s] <engine.exe> [<engine directory>]\n", sc-32); exit(-1); }\r
525         if(argc > 2) dir = argv[2];\r
526         if(argc > 3) suffix = argv[3];\r
527 \r
528         // spawn engine proc\r
529         if(StartEngine(argv[1], dir) != NO_ERROR) { perror(argv[1]), exit(-1); }\r
530 \r
531         Sync(INIT);\r
532 \r
533         // create separate thread to handle engine->GUI traffic\r
534 #ifdef WIN32\r
535         CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE) Engine2GUI, (LPVOID) NULL, 0, &thread_id);\r
536 #else\r
537         { pthread_t t; signal(SIGINT, SIG_IGN); pthread_create(&t, NULL, Engine2GUI, NULL); }\r
538 #endif\r
539 \r
540         // handle GUI->engine traffic in original thread\r
541         GUI2Engine();\r
542 }\r