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