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