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