Bump version to 4.0
[uci2wb.git] / UCI2WB.c
index 3baeeba..a546859 100644 (file)
--- a/UCI2WB.c
+++ b/UCI2WB.c
@@ -1,6 +1,15 @@
-/************************* UCI2WB by H.G.Muller ****************************/\r
-\r
-#define VERSION "2.0"\r
+/****************************************************************************/\r
+/*                           UCI2WB by H.G.Muller                           */\r
+/*                                                                          */\r
+/* UCI2WB is an adapter to run engines that communicate in various dialects */\r
+/* of the Universal Chess Interface in a GUI that supports XBoard protocol  */\r
+/* (CECP). It supports UCI (when used for Xiangqi: the 'Cyclone dialect'),  */\r
+/* as well as USI and UCCI when used with the flags -s or -x, respectively. */\r
+/* This version of UCI2WB is released under the GNU General Public License, */\r
+/* of which you should have received a copy together with this file.        */\r
+/****************************************************************************/\r
+\r
+#define VERSION "4.0"\r
 \r
 #include <stdio.h>\r
 #include <stdlib.h>\r
 #include <string.h>\r
 \r
 // Set VARIANTS for in WinBoard variant feature. (With -s option this will always be reset to use "shogi".)\r
-#  define VARIANTS "normal,xiangqi"\r
+#define VARIANTS ",normal,xiangqi"\r
+#define STDVARS "chess,chess960,crazyhouse,3check,giveaway,suicide,losers,atomic,seirawan,shogi,xiangqi"\r
+#define EGT ",gaviotaTbPath,syzygyPath,nalimovPath,robbotripleBaseDirectory,robbototalBaseDirectory,bitbases path,"\r
 \r
 #define DPRINT if(debug) printf\r
+#define EPRINT(X) { char f[999]; sprintf X; DPRINT("%s", f); fprintf(toE, "%s", f + 2*(*f == '#')); /* strip optional # prefix */ }\r
 \r
 #define WHITE 0\r
 #define BLACK 1\r
 #define NONE  2\r
 #define ANALYZE 3\r
 \r
-char move[2000][10], checkOptions[8192], iniPos[256], hashOpt[20], pause, pondering, suspended, ponder, post, hasHash, c, sc='c', *suffix, *variants;\r
-int mps, tc, inc, sTime, depth, myTime, hisTime, stm, computer = NONE, memory, oldMem=0, cores, moveNr, lastDepth, lastScore, startTime, debug;\r
-int statDepth, statScore, statNodes, statTime, currNr, size, collect, nr, sm, inex, on[500];\r
-char currMove[20], moveMap[500][10], /* for analyze mode */ canPonder[20], threadOpt[20];\r
-char board[100];  // XQ board for UCCI\r
+char move[2000][10], iniPos[256], hashOpt[20], suspended, ponder, post, hasHash, c, sc='c', suffix[81], varOpt, searching, *binary;\r
+int mps, tc, inc, sTime, depth, myTime, hisTime, stm, computer = NONE, memory, oldMem=0, cores, moveNr, lastDepth, lastScore, startTime, debug, flob;\r
+int statDepth, statScore, statNodes, statTime, currNr, size, collect, nr, sm, inex, on[500], frc, byo = -1, namOpt, comp;\r
+char currMove[20], moveMap[500][10], /* for analyze mode */ canPonder[20], threadOpt[20], varList[8000], anaOpt[20], checkOptions[8192] = "Ponder";\r
+char pvs[99][999], board[100];  // XQ board for UCCI\r
 char *nameWord = "name ", *valueWord = "value ", *wTime = "w", *bTime = "b", *wInc = "winc", *bInc = "binc", newGame; // keywords that differ in UCCI\r
-int unit = 1, drawOffer;\r
+int unit = 1, drawOffer, scores[99], mpvSP, maxDepth, ponderAlways;\r
 \r
 FILE *toE, *fromE, *fromF;\r
 int pid;\r
 \r
+char *strcasestr (char *p, char *q) { while(*p) { char *r=p++, *s=q; while(tolower(*r++) == tolower(*s) && *s) s++; if(!*s) return p-1; } return NULL; }\r
+\r
 #ifdef WIN32\r
 WinPipe(HANDLE *hRd, HANDLE *hWr)\r
 {\r
@@ -132,25 +146,25 @@ StartSearch(char *ponder)
        int x = (ponder[0] != 0);                   // during ponder stm is the opponent\r
        int black = (stm == BLACK ^ x ^ sc == 's'); // set if our color is what the engine calls black\r
        int nr = moveNr + x;                        // we ponder for one move ahead!\r
+       int t = (flob ? inc + myTime/40 : 1000*byo*(byo>0)); // byoyomi time \r
        if(sc == 'x') black = 1; else drawOffer = 0;// in UCCI 'black' refers to us and 'white' to opponent\r
        if(!x && drawOffer) ponder = " draw", drawOffer = 0; //pass draw offer only when not pondering\r
-       fprintf(toE, "\ngo%s %stime %d %stime %d", ponder, bTime, black ? myTime : hisTime, wTime, !black ? myTime : hisTime);\r
-       DPRINT(    "\n# go%s %stime %d %stime %d", ponder, bTime, black ? myTime : hisTime, wTime, !black ? myTime : hisTime);\r
-       if(sTime > 0) { fprintf(toE, " movetime %d", sTime); DPRINT(" movetime %d", sTime); } else\r
-       if(mps) { fprintf(toE, " movestogo %d", mps*(nr/(2*mps)+1)-nr/2); DPRINT(" movestogo %d", mps*(nr/(2*mps)+1)-nr/2); }\r
-       if(inc && !suffix) { fprintf(toE, " %s %d %s %d", wInc, inc, bInc, inc); DPRINT(" %s %d %s %d", wInc, inc, bInc, inc); }\r
-       if(depth > 0) { fprintf(toE, " depth %d", depth); DPRINT(" depth %d", depth); }\r
-        if(suffix) { fprintf(toE, suffix, inc); DPRINT(suffix, inc); }\r
-       fprintf(toE, "\n"); DPRINT("\n");\r
+       EPRINT((f, "# go%s %stime %d %stime %d", ponder, bTime, (black ? myTime : hisTime) - t, wTime, (!black ? myTime : hisTime) - t))\r
+       if(sTime > 0) EPRINT((f, " movetime %d", sTime)) else\r
+       if(mps) EPRINT((f, " movestogo %d", mps*(nr/(2*mps)+1)-nr/2))\r
+       if(flob || byo >= 0) sprintf(suffix, " byoyomi %d", t); // for engines running purely on byoyomi\r
+       if(inc && !*suffix) EPRINT((f, " %s %d %s %d", wInc, inc, bInc, inc))\r
+       if(depth > 0) EPRINT((f, " depth %d", depth))\r
+        if(*suffix) EPRINT((f, suffix, inc))\r
+       EPRINT((f, "\n")); maxDepth = mpvSP = 0;\r
 }\r
 \r
 void\r
-StopPonder(int pondering)\r
+StopSearch(int discard)\r
 {\r
-       if(!pondering) return;\r
-       pause = 2;\r
-       fprintf(toE, "stop\n"); fflush(toE); DPRINT("# stop\n"); // note: 'pondering' remains set until engine acknowledges 'stop' with 'bestmove'\r
-       Sync(PAUSE); // wait for engine to acknowledge 'stop' with 'bestmove'.\r
+       if(!searching) return;\r
+       if(discard) searching = 0; // this causes bestmove to be ignored\r
+       EPRINT((f, "# stop\n")) fflush(toE); // note: 'pondering' remains set until engine acknowledges 'stop' with 'bestmove'\r
 }\r
 \r
 void\r
@@ -163,20 +177,26 @@ LoadPos(int moveNr)
            stm = (!strstr(iniPos+4, " b ") ^ lastCapt & 1 ? 'w' :  'b');\r
            sprintf(buf, "position fen %s", ToFEN(stm)); pos = buf; // send it as FEN (with "position" in UCCI!)\r
        }\r
-       fprintf(toE, "%s moves", pos);\r
-       DPRINT(    "# %s moves", pos);\r
-       for(j=lastCapt; j<moveNr; j++) { fprintf(toE, " %s", move[j]); DPRINT(" %s", move[j]); }\r
+       EPRINT((f, "# %s moves", pos))\r
+       for(j=lastCapt; j<moveNr; j++) EPRINT((f, " %s", move[j]))\r
+       EPRINT((f, "\n"))\r
 }\r
 \r
 void\r
-StartPonder()\r
+StartPonder(int moveNr)\r
 {\r
        if(!move[moveNr][0]) return; // no ponder move\r
        LoadPos(moveNr+1);\r
-       pondering = 1; lastDepth = 1;\r
+       searching = 1; lastDepth = 1;\r
        StartSearch(" ponder");\r
 }\r
 \r
+void\r
+Analyze(char *val)\r
+{\r
+    if(*anaOpt) EPRINT((f, "# setoption %s%s %s%s\n", nameWord, anaOpt, valueWord, val));\r
+}\r
+\r
 char *Convert(char *pv)\r
 {   // convert Shogi coordinates to WB\r
     char *p, *q, c;\r
@@ -210,70 +230,69 @@ Move4GUI(char *m)
 }\r
 \r
 int\r
-GetChar()\r
+ReadLine (FILE *f, char *line)\r
 {\r
-    int c;\r
-    if(fromF) {\r
-       if((c = fgetc(fromF)) != EOF) return c;\r
-       fclose(fromF); fromF = 0; printf("# end fake\n");\r
-    }\r
-    return fgetc(fromE);\r
+    int x, i = 0;\r
+    while((x = fgetc(f)) != EOF && (line[i] = x) != '\n') i++; line[++i] = 0;\r
+    return (x != EOF);\r
 }\r
 \r
-void *\r
-Engine2GUI()\r
+void\r
+HandleEngineOutput()\r
 {\r
-    char line[1024], command[256];\r
+    char line[1024], command[256]; static char egts[999];\r
 \r
-    if(fromF = fopen("DefectiveEngineOptions.ini", "r")) printf("# fake engine input\n");\r
     while(1) {\r
-       int i=0, x; char *p, dummy;\r
+       int i=0, x; char *p, dummy, len;\r
 \r
        fflush(stdout); fflush(toE);\r
-       while((line[i] = x = GetChar()) != EOF && line[i] != '\n') i++;\r
-       line[++i] = 0;\r
-       if(x == EOF) exit(0);\r
+       if(fromF && !ReadLine(fromF, line))  fromF = 0, printf("# end fake\n");\r
+       if(!fromF && !ReadLine(fromE, line)) printf("tellusererror UCI2WB: %s died on me\n", binary), exit(0);\r
        DPRINT("# engine said: %s", line), fflush(stdout);\r
        if(sscanf(line, "%s", command) != 1) continue;\r
        if(!strcmp(command, "bestmove")) {\r
-           if(pause) { pondering = pause = 0; Sync(WAKEUP); continue; } // bestmove was reply to ponder miss or analysis result; ignore.\r
-           else if(pondering) { pondering = 0; printf("%d 0 0 0 UCI violation! Engine moves during ponder\n", lastDepth+1); continue; } // ignore ponder search\r
+           if(searching == 1) { searching = 0; printf("%d 0 0 0 UCI violation! Engine moves during ponder\n", lastDepth+1); return; } // ignore ponder search\r
+           else if(searching != 3) { searching = 0; return; } // ponder miss or analysis result; ignore.\r
            // move was a move to be played\r
            if(p = strstr(line+8, " draw")) *p = 0, printf("offer draw\n"); // UCCI\r
            if(strstr(line+9, "resign")) { printf("resign\n"); computer = NONE; }\r
+           if(strstr(line+9, "win")) { printf("%s {claim}\n", stm== WHITE ? "1-0" :"0-1"); computer = NONE; } // USI\r
            if(strstr(line+9, "(none)") || strstr(line+9, "null") ||\r
               strstr(line+9, "0000")) { printf("%s\n", lastScore < -99999 ? "resign" : "1/2-1/2 {stalemate}"); computer = NONE; }\r
            sscanf(line, "bestmove %s", move[moveNr++]);\r
-           myTime -= (GetTickCount() - startTime)*1.02 + inc; // update own clock, so we can give correct wtime, btime with ponder\r
+           myTime -= (GetTickCount() - startTime)*1.02 - inc; // update own clock, so we can give correct wtime, btime with ponder\r
            if(mps && ((moveNr+1)/2) % mps == 0) myTime += tc; if(sTime) myTime = sTime; // new session or move starts\r
-           stm = WHITE+BLACK - stm;\r
+           stm = WHITE+BLACK - stm; searching = 0;\r
            // first start a new ponder search, if pondering is on and we have a move to ponder on\r
            if(p = strstr(line+9, "ponder")) {\r
              sscanf(p+7, "%s", move[moveNr]);\r
              if(computer != NONE && ponder) {\r
                DPRINT("# ponder on %s\n", move[moveNr]);\r
-               StartPonder();\r
+               StartPonder(moveNr);\r
              }\r
              p[-1] = '\n'; *p = 0; // strip off ponder move\r
            } else move[moveNr][0] = 0;\r
            Move4GUI(line+9);\r
            printf("move %s\n", line+9); // send move to GUI\r
+            if(move[moveNr][0]) printf("Hint: %s\n", move[moveNr]);\r
            if(lastScore == 100001 && iniPos[0] != 'f') { printf("%s {mate}\n", stm == BLACK ? "1-0" : "0-1"); computer = NONE; }\r
+           fflush(stdout); return;\r
        }\r
        else if(!strcmp(command, "info")) {\r
-           int d=0, s=0, t=0, n=0;\r
-           char *pv;\r
+           int d=0, s=0, t=(GetTickCount() - startTime)/10, n=1;\r
+           char *pv, varName[80];\r
            if(sscanf(line+5, "string times @ %c", &dummy) == 1) { printf("# %s", line+12); continue; }\r
-           if(collect && (pv = strstr(line+5, "currmove "))) {\r
-               if(p = strstr(line+5, "currmovenumber ")) {\r
-                   n = atoi(p+15);\r
-                   if(collect == 1 && n != 1) continue; // wait for move 1\r
-                   if(collect + (n == 1) > 2) { // done collecting\r
-                       if(inex && collect == 2) printf("%d 0 0 0 OK to exclude\n", lastDepth);\r
-                       collect = 3; continue;\r
-                   }\r
-                   collect = 2; on[nr=n] = 1; sscanf(pv+9, "%s", moveMap[n]); continue; // store move\r
+           if(sscanf(line+5, "string variant %s", varName) == 1) {\r
+               if(!strstr(STDVARS, varName)) {\r
+                   int files = 8, ranks = 8, hand = 0; char parent[80];\r
+                   if(p = strstr(line+18, " files ")) sscanf(p+7, "%d", &files);\r
+                   if(p = strstr(line+18, " ranks ")) sscanf(p+7, "%d", &ranks);\r
+                   if(p = strstr(line+18, " pocket ")) sscanf(p+8, "%d", &hand);\r
+                   if(p = strstr(line+18, " template ")) sscanf(p+10, "%s", parent); else strcpy(parent, "fairy");\r
+                   if(p = strstr(line+18, " startpos "))\r
+                       printf("setup (-) %dx%d+%d_%s %s", files, ranks, hand, parent, p+10);\r
                }\r
+               continue;\r
            }\r
            if(!post) continue;\r
            if(sscanf(line+5, "string %c", &dummy) == 1) printf("%d 0 0 0 %s", lastDepth, line+12); else {\r
@@ -283,20 +302,43 @@ Engine2GUI()
                if(p = strstr(line+4, " score "))      sscanf(p+7, "%d", &s), statScore = s;\r
                if(p = strstr(line+4, " nodes "))      sscanf(p+7, "%d", &n), statNodes = n;\r
                if(p = strstr(line+4, " time "))       sscanf(p+6, "%d", &t), t /= 10, statTime = t;\r
-               if(p = strstr(line+4, " currmove "))   sscanf(p+10,"%s", currMove);\r
-               if(p = strstr(line+4, " currmovenumber ")) sscanf(p+16,"%d", &currNr);\r
-               if(pv = strstr(line+4, " pv ")) // convert PV info to WB thinking output\r
+               if(pv = strstr(line+4, " pv ")) { // convert PV info to WB thinking output\r
+                 if(d > maxDepth) maxDepth = d, mpvSP = 0; else if(d < maxDepth) continue; // ignore depth regressions\r
+                 if(p = strstr(line+4, " upperbound ")) strcat(p, "?\n"); else\r
+                 if(p = strstr(line+4, " lowerbound ")) strcat(p, "!\n");\r
+                 for(i=0; i<mpvSP; i++) if(s == scores[i] && !strcmp(pvs[i], pv+4)) break; // check if duplicat\r
+                 if(i >= mpvSP) strncpy(pvs[mpvSP], pv+4, 998), scores[mpvSP++] = s,       // emit as thinking output if not\r
                    printf("%3d  %6d %6d %10d %s", lastDepth=d, lastScore=s, t, n, Convert(pv+4));\r
+               } else if(s == -100000) lastScore = s; // when checkmated score is valid even without PV (which might not come)\r
+           }\r
+           if(collect && (pv = strstr(line+4, " currmove "))) {\r
+               sscanf(pv+10,"%s", currMove);\r
+               if(p = strstr(line+4, " currmovenumber ")) {\r
+                   n = currNr = atoi(p+16);\r
+                   if(collect == 1 && n != 1) continue; // wait for move 1\r
+                   if(collect + (n == 1) > 2) { // done collecting\r
+                       if(inex && collect == 2) printf("%d 0 0 0 OK to exclude\n", lastDepth);\r
+                       collect = 3; continue;\r
+                   }\r
+                   collect = 2; on[nr=n] = 1; strcpy(moveMap[n], currMove); continue; // store move\r
+               }\r
            }\r
        }\r
        else if(!strcmp(command, "option")) { // USI option: extract data fields\r
            char name[80], type[80], buf[1024], val[256], *q;\r
-           int min=0, max=1e9;\r
+           int min=0, max=1e9; *val = 0;\r
            if(p = strstr(line+6, " type ")) sscanf(p+1, "type %s", type), *p = '\n';\r
            if(p = strstr(line+6, " min "))  sscanf(p+1, "min %d", &min), *p = '\n';\r
            if(p = strstr(line+6, " max "))  sscanf(p+1, "max %d", &max), *p = '\n';\r
            if(p = strstr(line+6, " default "))  sscanf(p+1, "default %[^\n]*", val), *p = '\n';\r
            if(!(p = strstr(line+6, " name "))) p = line+1; sscanf(p+6, "%[^\n]", name); // 'name' is omitted in UCCI\r
+           if(!strcasecmp(name, "UCI_Chess960")) { frc=2; continue; }\r
+           if(!strcasecmp(name, "UCI_Variant")) { if(p = strstr(line+6, " var ")) strcpy(varList, p); varOpt = 1; continue; }\r
+           if(!strcasecmp(name, "UCI_Opponent")) { namOpt = 1; continue; }\r
+           if(!strcasecmp(name+2, "I_AnalyseMode")) { strcpy(anaOpt, name); continue; }\r
+           if(frc< 0 && (strstr(name, "960") || strcasestr(name, "frc")) && !strcmp(type, "check")) {\r
+               EPRINT((f, "# setoption name %s value true\n", name)) strcpy(val, "true"); // set non-standard suspected FRC options\r
+           }\r
            if(!strcasecmp(name, "Threads")) { strcpy(threadOpt, name); continue; }\r
            if(!strcasecmp(name, "Ponder") || !strcasecmp(name, "USI_Ponder")) { strcpy(canPonder, name); continue; }\r
            if(!strcasecmp(name, "Hash") || !strcasecmp(name, "USI_Hash") || !strcasecmp(name, "hashsize")) {\r
@@ -306,8 +348,15 @@ Engine2GUI()
            }\r
            if(!strcasecmp(name, "newgame") && !strcmp(type, "button")) { newGame++; continue; }\r
            if(!strcasecmp(name, "usemillisec")) { unit = (!strcmp(val, "false") ? 2 : 1); continue; }\r
+           sprintf(buf, ",%s,", name); if(p = strcasestr(EGT, buf)) { // collect EGT formats\r
+               strcpy(buf, p); for(p=buf; *++p >='a';){} if(*p == ' ') strcpy(buf, ",scorpio"); *p = 0; strcat(egts, buf); continue; // clip at first non-lower-case\r
+           }\r
            // pass on engine-defined option as WB option feature\r
            if(!strcmp(type, "filename")) type[4] = 0;\r
+           else if(sc == 'c' && !strcmp(type, "string")) { // in UCI try to guess which strings are file or directory names\r
+               if(strcasestr(name, "file")) strcpy(type, "file"); else\r
+               if(strcasestr(name, "path") || strcasestr(name, "directory") || strcasestr(name, "folder")) strcpy(type, "path");\r
+           }\r
            sprintf(buf, "feature option=\"%s -%s", name, type); q = buf + strlen(buf);\r
            if(     !strcmp(type, "file")\r
                 || !strcmp(type, "string")) sprintf(q, " %s\"\n", val);\r
@@ -327,14 +376,23 @@ Engine2GUI()
            if(buf[0]) printf("%s", buf);\r
        }\r
        else if(!strcmp(command, "id")) {\r
-           char name[256];\r
+           static char name[256], version[256];\r
            if(sscanf(line, "id name %[^\n]", name) == 1) printf("feature myname=\"%s (U%cI2WB)\"\n", name, sc-32);\r
+           if(sscanf(line, "id version %[^\n]", version) == 1 && *name) printf("feature myname=\"%s %s (U%cI2WB)\"\n", name, version, sc-32);\r
        }\r
-       else if(!strcmp(command, "readyok")) { pause = 0; Sync(WAKEUP); } // resume processing of GUI commands\r
+       else if(!strcmp(command, "readyok")) return; // resume processing of GUI commands\r
        else if(sc == 'x'&& !strcmp(command, "ucciok") || sscanf(command, "u%ciok", &c)==1 && c==sc) {\r
+           char *p = varList, *q = varList;\r
+           while(*q && *q != '\n')  if(!strncmp(q, " var ", 5)) *p++ = ',', q +=5; // replace var keywords by commas\r
+                               else if(!strncmp(q-1, " chess ", 7)) strcpy(p, "normal"), p += 6, q += 5; // 'chess' is called 'normal' in CECP\r
+                               else *p++ = *q++; // copy other variant names unmodified\r
+           if(frc) sprintf(p, ",normal,fischerandom"), printf("feature oocastle=%d\n", frc<0); // unannounced FRC uses O-O castling\r
+           if(!*varList) strcpy(varList, sc=='s' ? ",shogi,5x5+5_shogi" : VARIANTS); // without clue guess liberally\r
+           printf("feature variants=\"%s\"\n", varList+1); // from UCI_Variant combo and/or UCI_Chess960 check options\r
+           if(*egts) printf("feature egt=\"%s\"\n", egts+1);\r
            printf("feature smp=1 memory=%d done=1\n", hasHash);\r
-           if(unit == 2) unit = 1, fprintf(toE, "setoption usemillisec true\n");\r
-           Sync(WAKEUP); // done with options\r
+           if(unit == 2) { unit = 1; EPRINT((f, "# setoption usemillisec true\n")) }\r
+           fflush(stdout); return; // done with options\r
        }\r
     }\r
 }\r
@@ -357,61 +415,149 @@ Move4Engine(char *m)
     }\r
 }\r
 \r
+void DoCommand ();\r
+char mySide;\r
+volatile char queue[10000], *qStart, *qEnd;\r
+\r
 void\r
-GUI2Engine()\r
+LaunchSearch()\r
 {\r
-    char line[256], command[256], *p, *q, *r;\r
-\r
-    while(1) {\r
-       int i, x;\r
+    int i;\r
 \r
-       if((computer == stm || computer == ANALYZE) && !suspended) {\r
+       if((computer == stm || computer == ANALYZE && !searching && sm != 1) && !suspended) {\r
            DPRINT("# start search\n");\r
            LoadPos(moveNr); fflush(stdout); // load position\r
            // and set engine thinking (note USI swaps colors!)\r
-           startTime = GetTickCount();\r
+           startTime = GetTickCount(); mySide = stm; // remember side we last played for\r
            if(computer == ANALYZE) {\r
-               fprintf(toE, "\ngo infinite"); DPRINT("\n# go infinite");\r
+               EPRINT((f, "# go infinite")); maxDepth = mpvSP = 0;\r
                if(sm & 1) { // some moves are disabled\r
-                   fprintf(toE, " searchmoves"); DPRINT(" searchmoves");\r
-                   for(i=1; i<nr; i++) if(on[i]) { fprintf(toE, " %s", moveMap[i]); DPRINT(" %s", moveMap[i]); }\r
+                   EPRINT((f, " searchmoves"))\r
+                   for(i=1; i<nr; i++) if(on[i]) EPRINT((f, " %s", moveMap[i]))\r
                }\r
-               fprintf(toE, "\n"); DPRINT("\n");\r
-           // code for searchmoves goes here\r
-           } else StartSearch("");\r
-       }\r
-      nomove:\r
+               EPRINT((f, "\n")) searching = 2; // suppresses spurious commands during analysis starting new searches\r
+           } else searching = 3, StartSearch(""); // request suspending of input processing while thinking\r
+       } else if(ponderAlways && computer == NONE) move[moveNr][0] = 0, StartPonder(moveNr-1);\r
+}\r
+\r
+void\r
+GUI2Engine()\r
+{\r
+    char line[256], command[256], *p;\r
+\r
+    while(1) {\r
+       int i, difficult;\r
+\r
+       for(difficult=0; !difficult; ) { // read and handle commands that can (or must) be handled during thinking\r
        fflush(toE); fflush(stdout);\r
-       i = 0; while((x = getchar()) != EOF && (line[i] = x) != '\n') i++;\r
-       line[++i] = 0; if(x == EOF) { printf("# EOF\n"); fprintf(toE, "quit\n"); exit(-1); }\r
+       if(!ReadLine(stdin, line)) printf("# EOF\n"), sprintf(line, "quit -1\n");\r
        sscanf(line, "%s", command);\r
-       if(!strcmp(command, "new")) {\r
-           computer = BLACK; moveNr = 0; depth = -1; move[0][0] = 0;\r
-           stm = WHITE; strcpy(iniPos, "position startpos");\r
-           if(memory != oldMem && hasHash) fprintf(toE, "setoption name %s %s%d\n", hashOpt, valueWord, memory);\r
-           oldMem = memory;\r
-           // we can set other options here\r
-           if(sc == 'x') { if(newGame) fprintf(toE, "setoption newgame\n"); } else // optional in UCCI\r
-           fprintf(toE, "u%cinewgame\n", sc); fflush(toE);\r
-           pause = 1; // wait for option settings to take effect\r
-           fprintf(toE, "isready\n"); fflush(toE);\r
-           Sync(PAUSE); // wait for readyok\r
+       if(!strcmp(command, "usermove")) { difficult--; break; } // for efficiency during game play, moves, time & otim are tried first\r
+       else if(!strcmp(command, "time"))   sscanf(line+4, "%d", &myTime),  myTime  = (10*myTime)/unit;\r
+       else if(!strcmp(command, "otim"))   sscanf(line+4, "%d", &hisTime), hisTime = (10*hisTime)/unit;\r
+       else if(!strcmp(command, "offer")) drawOffer = 1; // backlogged anyway, so this can be done instantly\r
+       else if(!strcmp(command, "post"))  post = 1;\r
+       else if(!strcmp(command, "nopost"))post = 0;\r
+       else if(!strcmp(command, ".")) {\r
+           printf("stat01: %d %d %d %d %d %s\n", statTime, statNodes, statDepth, nr-currNr, nr, currMove);\r
+       }\r
+       else if(!strcmp(command, "pause")) {\r
+           if(computer == stm) myTime -= GetTickCount() - startTime;\r
+           suspended = 1 + (searching == 1); // remember if we were pondering, and stop search ignoring bestmove\r
+           StopSearch(1);\r
+       }\r
+       else if(!strcmp(command, "xboard")) ;\r
+       else if(!strcmp(command, "random")) ;\r
+       else if(!strcmp(command, "accepted")) ;\r
+       else if(!strcmp(command, "rejected")) ;\r
+       else if(!strcmp(command, "book")) ;\r
+       else if(!strcmp(command, "ics")) ;\r
+       else if(!strcmp(command, "hint")) ;\r
+       else if(!strcmp(command, "computer")) comp = 1;\r
+       else { //convert easy & hard to "option" after treating their effect on the adapter\r
+         if(!strcmp(command, "easy")) {\r
+           if(*canPonder) ponder = 0, sprintf(command, "option"), sprintf(line, "option %s=0\n", canPonder); else continue;\r
+         }\r
+         else if(!strcmp(command, "hard")) {\r
+           if(*canPonder) ponder = 1, sprintf(command, "option"), sprintf(line, "option %s=1\n", canPonder); else continue;\r
+         }\r
+         if(!strcmp(command, "option")) {\r
+           if(sscanf(line+7, "UCI2WB debug output=%d", &debug) == 1) ; else\r
+           if(sscanf(line+7, "ponder always=%d", &ponderAlways) == 1) ; else\r
+           if(sscanf(line+7, "Floating Byoyomi=%d", &flob) == 1) ; else\r
+           if(sscanf(line+7, "Byoyomi=%d", &byo) == 1) ; else\r
+           difficult = 1;\r
+         }\r
+         else difficult = 1; // difficult command; terminate loop for easy ones\r
        }\r
-       else if(!strcmp(command, "usermove")) {\r
+       } // next command\r
+\r
+       // some commands that should never come during thinking can be safely processed here\r
+       if(difficult < 0) { // used as kludge to signal "usermove" was already matched\r
            sscanf(line, "usermove %s", command); // strips off linefeed\r
            Move4Engine(command);\r
            stm = WHITE+BLACK - stm; collect = (computer == ANALYZE); sm = 0;\r
            // when pondering we either continue the ponder search as normal search, or abort it\r
-           if(pondering || computer == ANALYZE) {\r
-               if(pondering && !strcmp(command, move[moveNr])) { // ponder hit\r
+           if(searching) { // move cannot come during think, so we are pondering or analysing\r
+               if(searching == 1 && !strcmp(command, move[moveNr])) { // ponder hit\r
                    char *draw = drawOffer ? " draw" : ""; drawOffer = 0;\r
-                   pondering = 0; moveNr++; startTime = GetTickCount(); // clock starts running now\r
-                   fprintf(toE, "ponderhit%s\n", draw); DPRINT("# ponderhit%s\n", draw);\r
-                   goto nomove;\r
+                   searching = 3; moveNr++; startTime = GetTickCount(); // clock starts running now\r
+                   EPRINT((f, "# ponderhit%s\n", draw)) fflush(toE); fflush(stdout);\r
+                   continue;\r
                }\r
-               StopPonder(1);\r
+               StopSearch(1);\r
            }\r
            strcpy(move[moveNr++], command); // possibly overwrites ponder move\r
+           *qEnd++ = '\n'; Sync(WAKEUP);    // make sure engine thread considers starting a search\r
+       } else\r
+       if(!strcmp(command, "resume")) {\r
+           if(suspended == 2) StartPonder(moveNr); // restart interrupted ponder search\r
+           suspended = 0;  *qEnd++ = '\n'; Sync(WAKEUP); // causes search to start in normal way if on move or analyzing\r
+       } else\r
+      {\r
+       DPRINT("# queue '%s', searching=%d\n", command, searching);\r
+       if(searching == 3) { // command arrived during thinking; order abort for 'instant commands'\r
+           if(!strcmp(command, "?") || !strcmp(command, "quit") ||\r
+              !strcmp(command, "force") || !strcmp(command, "result")) StopSearch(0);\r
+       } else StopSearch(1); // always abort pondering or analysis\r
+\r
+       // queue command for execution by engine thread\r
+       if(qStart == qEnd) qStart = qEnd = queue;\r
+       p = line; while(qEnd < queue+10000 && (*qEnd++ = *p++) != '\n') {}\r
+       Sync(WAKEUP);\r
+      }\r
+    }\r
+}\r
+\r
+void\r
+DoCommand ()\r
+{\r
+    char line[1024], command[256], *p, *q, *r, type[99];\r
+    int i;\r
+\r
+    p=line; while(qStart < qEnd && (*p++ = *qStart++) != '\n') {} *p = 0;\r
+    if(line[0] == '\n') return;\r
+    sscanf(line, "%s", command); DPRINT("# command %s\n", command), fflush(stdout);\r
+\r
+       if(!strcmp(command, "new")) {\r
+           computer = BLACK; moveNr = 0; depth = -1; move[0][0] = 0;\r
+           stm = WHITE; strcpy(iniPos, "position startpos"); frc &= ~1;\r
+           if(memory != oldMem && hasHash) EPRINT((f, "# setoption %s%s %s%d\n", nameWord, hashOpt, valueWord, memory))\r
+           oldMem = memory;\r
+           // we can set other options here\r
+           if(varOpt) EPRINT((f, "# setoption name UCI_Variant value chess\n"))\r
+           EPRINT((f, "# isready\n")) fflush(toE);\r
+           HandleEngineOutput(); // wait for readyok\r
+           if(sc == 'x') { if(newGame) EPRINT((f, "# setoption newgame\n")) } else // optional in UCCI\r
+           EPRINT((f, "# u%cinewgame\n", sc)) fflush(toE);\r
+       }\r
+       else if(!strcmp(command, "option")) {\r
+           char *p;\r
+           if(p = strchr(line, '=')) {\r
+               *p++ = 0;\r
+               if(strstr(checkOptions, line+7)) sprintf(p, "%s\n", atoi(p) ? "true" : "false");\r
+               EPRINT((f, "# setoption %s%s %s%s", nameWord, line+7, valueWord, p));\r
+           } else EPRINT((f, "# setoption %s%s\n", nameWord, line+7));\r
        }\r
        else if(!strcmp(command, "level")) {\r
            int sec = 0;\r
@@ -419,80 +565,78 @@ GUI2Engine()
            sscanf(line, "level %d %d %d", &mps, &tc, &inc);\r
            tc = (60*tc + sec)*1000; inc *= 1000; sTime = 0; tc /= unit; inc /= unit;\r
        }\r
-       else if(!strcmp(command, "option")) {\r
-           char name[80], *p;\r
-           if(sscanf(line+7, "UCI2WB debug output=%d", &debug) == 1) ; else\r
-           if(p = strchr(line, '=')) {\r
-               *p++ = 0;\r
-               if(strstr(checkOptions, line+7)) sprintf(p, "%s\n", atoi(p) ? "true" : "false");\r
-               fprintf(toE, "setoption name %s value %s", line+7, p); DPRINT("# setoption %s%s %s%s", nameWord, line+7, valueWord, p);\r
-           } else { fprintf(toE, "setoption %s%s\n", nameWord, line+7); DPRINT("# setoption %s%s\n", nameWord, line+7); }\r
-       }\r
        else if(!strcmp(command, "protover")) {\r
-           if(!variants) variants = sc=='s' ? "shogi,5x5+5_shogi" : VARIANTS;\r
-           printf("feature variants=\"%s\" setboard=1 usermove=1 debug=1 ping=1 reuse=0 exclude=1 pause=1 sigint=0 sigterm=0 done=0\n", variants);\r
+           printf("feature setboard=1 usermove=1 debug=1 ping=1 name=1 reuse=0 exclude=1 pause=1 sigint=0 sigterm=0 done=0\n");\r
            printf("feature option=\"UCI2WB debug output -check %d\"\n", debug);\r
-           fprintf(toE, sc == 'x' ? "ucci\n" : "u%ci\n", sc); fflush(toE); // prompt UCI engine for options\r
-           Sync(PAUSE); // wait for uciok\r
+           printf("feature option=\"ponder always -check %d\"\n", ponderAlways);\r
+           if(sc == 's') printf("feature option=\"Floating Byoyomi -check %d\"\nfeature option=\"Byoyomi -spin %d -1 1000\"\n", flob, byo);\r
+           EPRINT((f, sc == 'x' ? "# ucci\n" : "# u%ci\n", sc)) fflush(toE); // prompt UCI engine for options\r
+           HandleEngineOutput(); // wait for uciok\r
        }\r
        else if(!strcmp(command, "setboard")) {\r
                stm = (strstr(line+9, " b ") ? BLACK : WHITE);\r
-                if(p = strchr(line+9, '[')) { char c;\r
+                if((p = strchr(line+9, '[')) && !varOpt) { char c;\r
                     *p++ = 0; q = strchr(p, ']'); *q = 0; r = q + 4; \r
                    if(sc == 's') q[2] = 'w' + 'b' - q[2], strcpy(r=q+3, " 1\n"); // Shogi: reverse color\r
                    else r = strchr(strchr(q+4, ' ') + 1, ' '); // skip to second space (after e.p. square)\r
                    *r = 0; sprintf(command, "%s%s %s %s", line+9, q+1, p, r+1);\r
                 } else strcpy(command, line+9);\r
+               if(frc == -1 && (p = strchr(command, ' '))) strncpy(p+3, "KQkq", 4); // unannounced FRC\r
                sprintf(iniPos, "%s%sfen %s", iniPos[0]=='p' ? "position " : "", sc=='s' ? "s" : "", command);\r
                iniPos[strlen(iniPos)-1] = sm = 0; collect = (computer == ANALYZE);\r
        }\r
        else if(!strcmp(command, "variant")) {\r
+               if(varOpt) {\r
+                   EPRINT((f, "# setoption name UCI_Variant value %sucinewgame\nisready\n", line+8))\r
+                   fflush(toE); HandleEngineOutput(); // wait for readyok\r
+               }\r
                if(!strcmp(line+8, "shogi\n")) size = 9, strcpy(iniPos, "position startpos");\r
                if(!strcmp(line+8, "5x5+5_shogi\n")) size = 5, strcpy(iniPos, "position startpos");\r
                if(!strcmp(line+8, "xiangqi\n")) strcpy(iniPos, "fen rnbakabnr/9/1c5c1/p1p1p1p1p/9/9/P1P1P1P1P/1C5C1/9/RNBAKABNR r");\r
+               if(!strcmp(line+8, "fischerandom\n")) { frc |= 1; if(frc > 0) EPRINT((f, "# setoption name UCI_Chess960 value true\n")) }\r
        }\r
        else if(!strcmp(command, "undo") && (i=1) || !strcmp(command, "remove") && (i=2)) {\r
-           if(pondering || computer == ANALYZE) StopPonder(1);\r
            moveNr = moveNr > i ? moveNr - i : 0; collect = (computer == ANALYZE); sm = 0;\r
        }\r
-       else if(!strcmp(command, ".")) {\r
-           printf("stat01: %d %d %d %d 100 %s\n", statTime, statNodes, statDepth, 100-currNr, currMove);\r
-           goto nomove;\r
-       }\r
        else if(!strcmp(command+2, "clude") && collect > 2) { // include or exclude\r
            int all = !strcmp(line+8, "all"), in = command[1] == 'n';\r
            inex = 1; line[strlen(line)-1] = sm = 0; // strip LF and clear sm flag\r
            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
-           if(!(sm & 2)) goto nomove; // no moves enabled; continue current search\r
-           if(computer == ANALYZE) StopPonder(1); // abort old analysis\r
        }\r
-       else if(!strcmp(command, "pause")) {\r
-           if(computer == stm) myTime -= GetTickCount() - startTime;\r
-           suspended = 1 + pondering; // remember if we were pondering, and stop search ignoring bestmove\r
-           StopPonder(pondering || computer == stm);\r
-       }\r
-       else if(!strcmp(command, "resume")) {\r
-           if(suspended == 2) StartPonder(); // restart interrupted ponder search\r
-           suspended = 0; // causes thinking to start in normal way if on move or analyzing\r
-       }\r
-       else if(!strcmp(command, "xboard")) ;\r
-       else if(!strcmp(command, "analyze"))computer = ANALYZE, collect = 1, sm = 0;\r
-       else if(!strcmp(command, "exit"))   computer = NONE, StopPonder(1);\r
-       else if(!strcmp(command, "force"))  computer = NONE, StopPonder(pondering);\r
+       else if(!strcmp(command, "analyze"))computer = ANALYZE, collect = 1, sm = 0, Analyze("true");\r
+       else if(!strcmp(command, "exit"))   computer = NONE, Analyze("false");\r
+       else if(!strcmp(command, "force"))  computer = NONE;\r
        else if(!strcmp(command, "go"))     computer = stm;\r
-       else if(!strcmp(command, "time"))   sscanf(line+4, "%d", &myTime),  myTime  = (10*myTime)/unit;\r
-       else if(!strcmp(command, "otim"))   sscanf(line+4, "%d", &hisTime), hisTime = (10*hisTime)/unit;\r
-       else if(!strcmp(command, "post"))   post = 1;\r
-       else if(!strcmp(command, "nopost")) post = 0;\r
-       else if(!strcmp(command, "easy") && !!*canPonder) ponder = 0, StopPonder(pondering), fprintf(toE, "setoption %s%s %sfalse\n", nameWord, canPonder, valueWord);\r
-       else if(!strcmp(command, "hard") && !!*canPonder) ponder = 1, fprintf(toE, "setoption %s%s %strue\n", nameWord, canPonder, valueWord), StartPonder();\r
-       else if(!strcmp(command, "ping"))   { static int done; if(!done) pause = 1, fprintf(toE, "isready\n"), fflush(toE), printf("# send isready\n"), fflush(stdout), Sync(PAUSE); done = 1; printf("pong %s", line+5); }\r
+       else if(!strcmp(command, "ping"))   { /* static int done; if(!done) pause = 1, fprintf(toE, "isready\n"), fflush(toE), printf("# send isready\n"), fflush(stdout), Sync(PAUSE); done = 1;*/ printf("po%s", line+2); }\r
        else if(!strcmp(command, "memory")) sscanf(line, "memory %d", &memory);\r
-       else if(!strcmp(command, "cores")&& !!*threadOpt) sscanf(line, "cores %d", &cores), fprintf(toE, "setoption %s%s %s%d\n", nameWord, threadOpt, valueWord, cores);\r
+       else if(!strcmp(command, "cores")&& !!*threadOpt) { sscanf(line, "cores %d", &cores); EPRINT((f, "# setoption %s%s %s%d\n", nameWord, threadOpt, valueWord, cores)) }\r
+       else if(!strcmp(command, "egtpath")){\r
+           sscanf(line+8, "%s %[^\n]", type, command);\r
+            if(p = strstr(EGT, type)) strcpy(type, p), p = strchr(type, ','), *p = 0; else strcpy(type, "bitbases path");\r
+           EPRINT((f, "# setoption name %s value %s\n", type, command));\r
+       }\r
        else if(!strcmp(command, "sd"))     sscanf(line, "sd %d", &depth);\r
        else if(!strcmp(command, "st"))     sscanf(line, "st %d", &sTime), sTime = 1000*sTime - 30, inc = 0, sTime /= unit;\r
-       else if(!strcmp(command, "offer"))  drawOffer = 1;\r
-       else if(!strcmp(command, "quit"))   fprintf(toE, "quit\n"), fflush(toE), exit(0);\r
+       else if(!strcmp(command, "name"))   { if(namOpt) EPRINT((f, "# setoption name UCI_Opponent value none none %s %s", comp ? "computer" : "human", line+5)) }\r
+       else if(!strcmp(command, "result")) {\r
+           if(sc == 's') EPRINT((f, "# gameover %s\n", line[8] == '/' ? "draw" : (line[7] == '0') == mySide ? "win" : "lose"))\r
+           computer = NONE;\r
+       }\r
+       else if(!strcmp(command, "quit"))   { EPRINT((f, "# quit\n")) fflush(toE), exit(atoi(line+4)); }\r
+       else printf("Error (unknown command): %s\n", command);\r
+\r
+       fflush(stdout);\r
+}\r
+\r
+void *\r
+Engine2GUI()\r
+{\r
+    if(fromF = fopen("DefectiveEngineOptions.ini", "r")) printf("# fake engine input\n");\r
+    while(1) {\r
+       if(searching > 1) HandleEngineOutput();  // this could leave us (or fall through) pondering\r
+       while(qStart == qEnd && searching) HandleEngineOutput(); // relay ponder output until command arrives\r
+       Sync(PAUSE); // possibly wait for command silently if engine is idle\r
+       DoCommand(); LaunchSearch();\r
     }\r
 }\r
 \r
@@ -585,18 +729,21 @@ main(int argc, char **argv)
 {\r
        char *dir = NULL, *p, *q; int e;\r
 \r
+\r
        if(argc == 2 && !strcmp(argv[1], "-v")) { printf("UCI2WB " VERSION " by H.G.Muller\n"); exit(0); }\r
        if(argc > 1 && !strcmp(argv[1], "debug")) { debug = 1; argc--; argv++; }\r
-       if(argc > 1 && !strcmp(argv[1], "-var")) { variants = argv[2]; argc-=2; argv+=2; }\r
+       if(argc > 1 && !strcmp(argv[1], "-var")) { strcpy(varList+1, argv[2]); *varList = ','; argc-=2; argv+=2; }\r
        if(argc > 1 && argv[1][0] == '-') { sc = argv[1][1]; argc--; argv++; }\r
        if(argc < 2) { printf("usage is: U%cI2WB [debug] [-s] <engine.exe> [<engine directory>]\n", sc-32); exit(-1); }\r
        if(argc > 2) dir = argv[2];\r
-        if(argc > 3) suffix = argv[3];\r
+        if(argc > 3) strncpy(suffix, argv[3], 80);\r
 \r
         if(sc == 'x') nameWord = valueWord = bTime = "", wTime = "opp", bInc = "increment", wInc = "oppincrement", unit = 1000; // switch to UCCI keywords\r
+       else if(sc == 'f' ) frc = -1, sc = 'c';   // UCI for unannounced Chess960\r
+       else if(sc == 'n') sc = 'c'; // UCI for normal Chess\r
 \r
        // spawn engine proc\r
-       if(StartEngine(argv[1], dir) != NO_ERROR) { perror(argv[1]), exit(-1); }\r
+       if(StartEngine(binary = argv[1], dir) != NO_ERROR) { perror(argv[1]), exit(-1); }\r
 \r
        Sync(INIT);\r
 \r