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