725606198a78013786e23cacd21a3c9c8b4e7171
[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];\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, "Ponder") || !strcmp(name, "USI_Ponder")) { strcpy(canPonder, name); continue; }\r
242             if(!strcmp(name, "Hash") || !strcmp(name, "USI_Hash")) {\r
243                 memory = oldMem = atoi(val); hasHash = 1; \r
244                 strcpy(hashOpt, name);\r
245                 continue;\r
246             }\r
247             // pass on engine-defined option as WB option feature\r
248             if(!strcmp(type, "filename")) type[4] = 0;\r
249             sprintf(buf, "feature option=\"%s -%s", name, type); q = buf + strlen(buf);\r
250             if(     !strcmp(type, "file")\r
251                  || !strcmp(type, "string")) sprintf(q, " %s\"\n", val);\r
252             else if(!strcmp(type, "spin"))   sprintf(q, " %d %d %d\"\n", atoi(val), min, max);\r
253             else if(!strcmp(type, "check"))  sprintf(q, " %d\"\n", strcmp(val, "true") ? 0 : 1), strcat(checkOptions, name);\r
254             else if(!strcmp(type, "button")) sprintf(q, "\"\n");\r
255             else if(!strcmp(type, "combo")) {\r
256                 if(p = strstr(line+6, " default "))  sscanf(p+1, "default %s", type); // current setting\r
257                 min = 0; p = line+6;\r
258                 while(p = strstr(p, " var ")) {\r
259                     sscanf(p += 5, "%s", val); // next choice\r
260                     sprintf(buf + strlen(buf), "%s%s%s", min++ ? " /// " : " ", strcmp(type, val) ? "" : "*", val);\r
261                 }\r
262                 strcat(q, "\"\n");\r
263             }\r
264             else buf[0] = 0; // ignore unrecognized option types\r
265             if(buf[0]) printf("%s", buf);\r
266         }\r
267         else if(!strcmp(command, "id")) {\r
268             char name[256];\r
269             if(sscanf(line, "id name %[^\n]", name) == 1) printf("feature myname=\"%s (U%cI2WB)\"\n", name, sc-32);\r
270         }\r
271         else if(!strcmp(command, "readyok")) { pause = 0; Sync(WAKEUP); } // resume processing of GUI commands\r
272         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
273     }\r
274 }\r
275 \r
276 void\r
277 Move4Engine(char *m)\r
278 {\r
279     if(sc == 's') {\r
280       // convert input move to USI format\r
281       if(m[1] == '@') { // drop\r
282         m[1] = '*';\r
283       } else {\r
284         m[0] = 'a'+'0'+size - m[0];\r
285         m[1] = 'a'+'0'+size - m[1];\r
286       }\r
287       m[2] = 'a'+'0'+size - m[2];\r
288       m[3] = 'a'+'0'+size - m[3];\r
289       if(m[4] == '=') m[4] = 0; // no '=' in USI format!\r
290       else if(m[4]) m[4] = '+'; // cater to WB 4.4 bug :-(\r
291     }\r
292 }\r
293 \r
294 void\r
295 GUI2Engine()\r
296 {\r
297     char line[256], command[256], *p, *q, *r;\r
298 \r
299     while(1) {\r
300         int i, x;\r
301 \r
302         if((computer == stm || computer == ANALYZE) && !suspended) {\r
303             DPRINT("# start search\n");\r
304             LoadPos(moveNr); // load position\r
305             // and set engine thinking (note USI swaps colors!)\r
306             startTime = GetTickCount();\r
307             if(computer == ANALYZE) {\r
308                 fprintf(toE, "\ngo infinite"); DPRINT("\n# go infinite");\r
309                 if(sm & 1) { // some moves are disabled\r
310                     fprintf(toE, " searchmoves"); DPRINT(" searchmoves");\r
311                     for(i=1; i<nr; i++) if(on[i]) { fprintf(toE, " %s", moveMap[i]); DPRINT(" %s", moveMap[i]); }\r
312                 }\r
313                 fprintf(toE, "\n"); DPRINT("\n");\r
314             // code for searchmoves goes here\r
315             } else StartSearch("");\r
316         }\r
317       nomove:\r
318         fflush(toE); fflush(stdout);\r
319         i = 0; while((x = getchar()) != EOF && (line[i] = x) != '\n') i++;\r
320         line[++i] = 0; if(x == EOF) { printf("# EOF\n"); exit(-1); }\r
321         sscanf(line, "%s", command);\r
322         if(!strcmp(command, "new")) {\r
323             computer = BLACK; moveNr = 0; depth = -1; move[0][0] = 0;\r
324             stm = WHITE; strcpy(iniPos, "position startpos");\r
325             if(memory != oldMem && hasHash) fprintf(toE, "setoption name %s value %d\n", hashOpt, memory);\r
326             oldMem = memory;\r
327             // we can set other options here\r
328             pause = 1; // wait for option settings to take effect\r
329             fprintf(toE, "isready\n");\r
330             fprintf(toE, "u%cinewgame\n", sc); fflush(toE);\r
331             Sync(PAUSE); // wait for readyok\r
332         }\r
333         else if(!strcmp(command, "usermove")) {\r
334             sscanf(line, "usermove %s", command); // strips off linefeed\r
335             Move4Engine(command);\r
336             stm = WHITE+BLACK - stm; collect = (computer == ANALYZE); sm = 0;\r
337             // when pondering we either continue the ponder search as normal search, or abort it\r
338             if(pondering || computer == ANALYZE) {\r
339                 if(pondering && !strcmp(command, move[moveNr])) { // ponder hit\r
340                     pondering = 0; moveNr++; startTime = GetTickCount(); // clock starts running now\r
341                     fprintf(toE, "ponderhit\n"); DPRINT("# ponderhit\n");\r
342                     goto nomove;\r
343                 }\r
344                 StopPonder(1);\r
345             }\r
346             strcpy(move[moveNr++], command); // possibly overwrites ponder move\r
347         }\r
348         else if(!strcmp(command, "level")) {\r
349             int sec = 0;\r
350             sscanf(line, "level %d %d:%d %d", &mps, &tc, &sec, &inc) == 4 ||\r
351             sscanf(line, "level %d %d %d", &mps, &tc, &inc);\r
352             tc = (60*tc + sec)*1000; inc *= 1000; sTime = 0;\r
353         }\r
354         else if(!strcmp(command, "option")) {\r
355             char name[80], *p;\r
356             if(sscanf(line+7, "UCI2WB debug output=%d", &debug) == 1) ; else\r
357             if(p = strchr(line, '=')) {\r
358                 *p++ = 0;\r
359                 if(strstr(checkOptions, line+7)) sprintf(p, "%s\n", atoi(p) ? "true" : "false");\r
360                 fprintf(toE, "setoption name %s value %s", line+7, p); DPRINT("# setoption name %s value %s", line+7, p);\r
361             } else { fprintf(toE, "setoption name %s\n", line+7); DPRINT("# setoption name %s\n", line+7); }\r
362         }\r
363         else if(!strcmp(command, "protover")) {\r
364             if(!variants) variants = sc=='s' ? "shogi,5x5+5_shogi" : VARIANTS;\r
365             printf("feature variants=\"%s\" setboard=1 usermove=1 debug=1 ping=1 reuse=0 exclude=1 pause=1 done=0\n", variants);\r
366             printf("feature option=\"UCI2WB debug output -check %d\"\n", debug);\r
367             fprintf(toE, "u%ci\n", sc); fflush(toE); // this prompts UCI engine for options\r
368             Sync(PAUSE); // wait for uciok\r
369         }\r
370         else if(!strcmp(command, "setboard")) {\r
371                 if(strstr(line+9, " b ")) stm = BLACK;\r
372                 if(p = strchr(line+9, '[')) { char c;\r
373                     *p++ = 0; q = strchr(p, ']'); *q = 0; r = q + 4; \r
374                     if(sc == 's') q[2] = 'w' + 'b' - q[2], strcpy(r=q+3, " 1\n"); // Shogi: reverse color\r
375                     else r = strchr(strchr(q+4, ' ') + 1, ' '); // skip to second space (after e.p. square)\r
376                     *r = 0; sprintf(command, "%s%s %s %s", line+9, q+1, p, r+1);\r
377                 } else strcpy(command, line+9);\r
378                 sprintf(iniPos, "%s%sfen %s", iniPos[0]=='p' ? "position " : "", sc=='s' ? "s" : "", command);\r
379                 iniPos[strlen(iniPos)-1] = sm = 0; collect = (computer == ANALYZE);\r
380         }\r
381         else if(!strcmp(command, "variant")) {\r
382                 if(!strcmp(line+8, "shogi\n")) size = 9, strcpy(iniPos, "position startpos");\r
383                 if(!strcmp(line+8, "5x5+5_shogi\n")) size = 5, strcpy(iniPos, "position startpos");\r
384                 if(!strcmp(line+8, "xiangqi\n")) strcpy(iniPos, "fen rnbakabnr/9/1c5c1/p1p1p1p1p/9/9/P1P1P1P1P/1C5C1/9/RNBAKABNR r");\r
385         }\r
386         else if(!strcmp(command, "undo") && (i=1) || !strcmp(command, "remove") && (i=2)) {\r
387             if(pondering || computer == ANALYZE) StopPonder(1);\r
388             moveNr = moveNr > i ? moveNr - i : 0; collect = (computer == ANALYZE); sm = 0;\r
389         }\r
390         else if(!strcmp(command, ".")) {\r
391             printf("stat01: %d %d %d %d 100 %s\n", statTime, statNodes, statDepth, 100-currNr, currMove);\r
392             goto nomove;\r
393         }\r
394         else if(!strcmp(command+2, "clude") && collect > 2) { // include or exclude\r
395             int all = !strcmp(line+8, "all"), in = command[1] == 'n';\r
396             inex = 1; line[strlen(line)-1] = sm = 0; // strip LF and clear sm flag\r
397             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
398             if(!(sm & 2)) goto nomove; // no moves enabled; continue current search\r
399             if(computer == ANALYZE) StopPonder(1); // abort old analysis\r
400         }\r
401         else if(!strcmp(command, "pause")) {\r
402             if(computer == stm) myTime -= GetTickCount() - startTime;\r
403             suspended = 1 + pondering; // remember if we were pondering, and stop search ignoring bestmove\r
404             StopPonder(pondering || computer == stm);\r
405         }\r
406         else if(!strcmp(command, "resume")) {\r
407             if(suspended == 2) StartPonder(); // restart interrupted ponder search\r
408             suspended = 0; // causes thinking to start in normal way if on move or analyzing\r
409         }\r
410         else if(!strcmp(command, "xboard")) ;\r
411         else if(!strcmp(command, "analyze"))computer = ANALYZE, collect = 1, sm = 0;\r
412         else if(!strcmp(command, "exit"))   computer = NONE, StopPonder(1);\r
413         else if(!strcmp(command, "force"))  computer = NONE, StopPonder(pondering);\r
414         else if(!strcmp(command, "go"))     computer = stm;\r
415         else if(!strcmp(command, "time"))   sscanf(line+4, "%d", &myTime),  myTime  *= 10;\r
416         else if(!strcmp(command, "otim"))   sscanf(line+4, "%d", &hisTime), hisTime *= 10;\r
417         else if(!strcmp(command, "post"))   post = 1;\r
418         else if(!strcmp(command, "nopost")) post = 0;\r
419         else if(!strcmp(command, "easy") && !!*canPonder) ponder = 0, StopPonder(pondering), fprintf(toE, "setoption name %s value false\n", canPonder);\r
420         else if(!strcmp(command, "hard") && !!*canPonder) ponder = 1, fprintf(toE, "setoption name %s value true\n", canPonder), StartPonder();\r
421         else if(!strcmp(command, "ping"))   pause = 1, fprintf(toE, "isready\n"), fflush(toE), Sync(PAUSE), printf("pong %s", line+5);\r
422         else if(!strcmp(command, "memory")) sscanf(line, "memory %d", &memory);\r
423         else if(!strcmp(command, "cores"))  sscanf(line, "cores %d", &cores);\r
424         else if(!strcmp(command, "sd"))     sscanf(line, "sd %d", &depth);\r
425         else if(!strcmp(command, "st"))     sscanf(line, "st %d", &sTime), sTime = 1000*sTime - 30, inc = 0;\r
426         else if(!strcmp(command, "quit"))   fprintf(toE, "quit\n"), fflush(toE), exit(0);\r
427     }\r
428 }\r
429 \r
430 int\r
431 StartEngine(char *cmdLine, char *dir)\r
432 {\r
433 #ifdef WIN32\r
434   HANDLE hChildStdinRd, hChildStdinWr,\r
435     hChildStdoutRd, hChildStdoutWr;\r
436   BOOL fSuccess;\r
437   PROCESS_INFORMATION piProcInfo;\r
438   STARTUPINFO siStartInfo;\r
439   DWORD err;\r
440 \r
441   /* Create a pipe for the child's STDOUT. */\r
442   if (! WinPipe(&hChildStdoutRd, &hChildStdoutWr)) return GetLastError();\r
443 \r
444   /* Create a pipe for the child's STDIN. */\r
445   if (! WinPipe(&hChildStdinRd, &hChildStdinWr)) return GetLastError();\r
446 \r
447   SetCurrentDirectory(dir); // go to engine directory\r
448 \r
449   /* Now create the child process. */\r
450   siStartInfo.cb = sizeof(STARTUPINFO);\r
451   siStartInfo.lpReserved = NULL;\r
452   siStartInfo.lpDesktop = NULL;\r
453   siStartInfo.lpTitle = NULL;\r
454   siStartInfo.dwFlags = STARTF_USESTDHANDLES;\r
455   siStartInfo.cbReserved2 = 0;\r
456   siStartInfo.lpReserved2 = NULL;\r
457   siStartInfo.hStdInput = hChildStdinRd;\r
458   siStartInfo.hStdOutput = hChildStdoutWr;\r
459   siStartInfo.hStdError = hChildStdoutWr;\r
460 \r
461   fSuccess = CreateProcess(NULL,\r
462                            cmdLine,        /* command line */\r
463                            NULL,           /* process security attributes */\r
464                            NULL,           /* primary thread security attrs */\r
465                            TRUE,           /* handles are inherited */\r
466                            DETACHED_PROCESS|CREATE_NEW_PROCESS_GROUP,\r
467                            NULL,           /* use parent's environment */\r
468                            NULL,\r
469                            &siStartInfo, /* STARTUPINFO pointer */\r
470                            &piProcInfo); /* receives PROCESS_INFORMATION */\r
471 \r
472   if (! fSuccess) return GetLastError();\r
473 \r
474 //  if (0) { // in the future we could trigger this by an argument\r
475 //    SetPriorityClass(piProcInfo.hProcess, GetWin32Priority(appData.niceEngines));\r
476 //  }\r
477 \r
478   /* Close the handles we don't need in the parent */\r
479   CloseHandle(piProcInfo.hThread);\r
480   CloseHandle(hChildStdinRd);\r
481   CloseHandle(hChildStdoutWr);\r
482 \r
483   process = piProcInfo.hProcess;\r
484   pid = piProcInfo.dwProcessId;\r
485   fromE = (FILE*) _fdopen( _open_osfhandle((long)hChildStdoutRd, _O_TEXT|_O_RDONLY), "r");\r
486   toE   = (FILE*) _fdopen( _open_osfhandle((long)hChildStdinWr, _O_WRONLY), "w");\r
487 #else\r
488     char *argv[10], *p, buf[200];\r
489     int i, toEngine[2], fromEngine[2];\r
490 \r
491     if (dir && dir[0] && chdir(dir)) { perror(dir); exit(1); }\r
492     pipe(toEngine); pipe(fromEngine); // create two pipes\r
493 \r
494     if ((pid = fork()) == 0) { // Child\r
495         dup2(toEngine[0], 0);   close(toEngine[0]);   close(toEngine[1]);   // stdin from toE pipe\r
496         dup2(fromEngine[1], 1); close(fromEngine[0]); close(fromEngine[1]); // stdout into fromE pipe\r
497         dup2(1, fileno(stderr)); // stderr into frome pipe\r
498 \r
499         strcpy(buf, cmdLine); p = buf;\r
500         for (i=0;;) { argv[i++] = p; p = strchr(p, ' '); if (p == NULL) break; *p++ = 0; }\r
501         argv[i] = NULL;\r
502         execvp(argv[0], argv); // startup engine\r
503         \r
504         perror(argv[0]); exit(1); // could not start engine; quit.\r
505     }\r
506     signal(SIGPIPE, SIG_IGN);\r
507     close(toEngine[0]); close(fromEngine[1]); // close engine ends of pipes in adapter\r
508     \r
509     fromE = (FILE*) fdopen(fromEngine[0], "r"); // make into high-level I/O\r
510     toE   = (FILE*) fdopen(toEngine[1], "w");\r
511 #endif\r
512   return NO_ERROR;\r
513 }\r
514 \r
515 main(int argc, char **argv)\r
516 {\r
517         char *dir = NULL, *p, *q; int e;\r
518 \r
519         if(argc == 2 && !strcmp(argv[1], "-v")) { printf("UCI2WB " VERSION " by H.G.Muller\n"); exit(0); }\r
520         if(argc > 1 && !strcmp(argv[1], "debug")) { debug = 1; argc--; argv++; }\r
521         if(argc > 1 && !strcmp(argv[1], "-var")) { variants = argv[2]; argc-=2; argv+=2; }\r
522         if(argc > 1 && argv[1][0] == '-') { sc = argv[1][1]; argc--; argv++; }\r
523         if(argc < 2) { printf("usage is: U%cI2WB [debug] [-s] <engine.exe> [<engine directory>]\n", sc-32); exit(-1); }\r
524         if(argc > 2) dir = argv[2];\r
525         if(argc > 3) suffix = argv[3];\r
526 \r
527         // spawn engine proc\r
528         if(StartEngine(argv[1], dir) != NO_ERROR) { perror(argv[1]), exit(-1); }\r
529 \r
530         Sync(INIT);\r
531 \r
532         // create separate thread to handle engine->GUI traffic\r
533 #ifdef WIN32\r
534         CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE) Engine2GUI, (LPVOID) NULL, 0, &thread_id);\r
535 #else\r
536         { pthread_t t; signal(SIGINT, SIG_IGN); pthread_create(&t, NULL, Engine2GUI, NULL); }\r
537 #endif\r
538 \r
539         // handle GUI->engine traffic in original thread\r
540         GUI2Engine();\r
541 }\r