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