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