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