Split multi-leg moves into two CECP move commands
[uci2wb.git] / UCI2WB.c
index 4cbf5a8..5cb07e8 100644 (file)
--- a/UCI2WB.c
+++ b/UCI2WB.c
@@ -9,7 +9,7 @@
 /* of which you should have received a copy together with this file.        */\r
 /****************************************************************************/\r
 \r
-#define VERSION "3.0"\r
+#define VERSION "4.1"\r
 \r
 #include <stdio.h>\r
 #include <stdlib.h>\r
 #  include <io.h>\r
    HANDLE process;\r
    DWORD thread_id;\r
+   void Bury(int s) { if(WaitForSingleObject(process, 1000*s+50) != WAIT_OBJECT_0) TerminateProcess(process, 0); }\r
 #else\r
 #  include <pthread.h>\r
 #  include <signal.h>\r
+#  include <unistd.h>\r
 #  define NO_ERROR 0\r
 #  include <sys/time.h>\r
+#  include <sys/wait.h>\r
    int GetTickCount() // with thanks to Tord\r
    { struct timeval t; gettimeofday(&t, NULL); return t.tv_sec*1000 + t.tv_usec/1000; }\r
+//#  include <unistd.h>\r
+   int Sleep(int msec) { return usleep(1000*msec); }\r
+   int pid; void Bury(int msec) { Sleep(msec+50); if(waitpid(-1, NULL, WNOHANG) <= 0) kill(pid, SIGKILL); }\r
 #endif\r
 #include <fcntl.h>\r
 #include <string.h>\r
+#include <ctype.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 STDVARS "chess,chess960,crazyhouse,3check,giveaway,suicide,losers,atomic,seirawan,shogi,xiangqi"\r
 #define EGT ",gaviotaTbPath,syzygyPath,nalimovPath,robbotripleBaseDirectory,robbototalBaseDirectory,bitbases path,"\r
+#define XQPOS "position fen rnbakabnr/9/1c5c1/p1p1p1p1p/9/9/P1P1P1P1P/1C5C1/9/RNBAKABNR"\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
 #define NONE  2\r
 #define ANALYZE 3\r
 \r
-char move[2000][10], iniPos[256], hashOpt[20], pause, pondering, suspended, ponder, post, hasHash, c, sc='c', suffix[81], varOpt, searching, *binary;\r
+char move[2000][10], iniPos[256], hashOpt[20], suspended, ponder, post, hasHash, c, sc=' ', sc2, 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], backLog[10000], checkOptions[8192] = "Ponder";\r
+int statDepth, statScore, statNodes, statTime, currNr, hsize=9, size=9, 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, scores[99], mpvSP, maxDepth, ponderAlways;\r
-volatile int logLen, sentLen;\r
+int unit = 1, drawOffer, scores[99], mpvSP, maxDepth, ponderAlways, newCnt, priority, killDelay;\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
@@ -86,12 +92,13 @@ Sync (int action)
            case PAUSE:  ReadFile(hRd, &c, 1, &d, NULL);\r
        }\r
 #else\r
-       static int syncPipe[2]; char c;\r
+       static int syncPipe[2], res;    char c;\r
        switch(action) {\r
-           case INIT:   pipe(syncPipe); break;\r
-           case WAKEUP: write(syncPipe[1], "\n", 1); break;\r
-           case PAUSE:  read(syncPipe[0], &c, 1);\r
+           case INIT:   res = pipe(syncPipe); break;\r
+           case WAKEUP: res = write(syncPipe[1], "\n", 1); break;\r
+           case PAUSE:  res = read(syncPipe[0], &c, 1);\r
        }\r
+       if(res < 0) printf("tellusererror UCI2WB: bad sync pipe\n"), exit(0);\r
 #endif\r
 }\r
 \r
@@ -132,7 +139,7 @@ int
 Play(int nr)\r
 {\r
        int i, last = -1;\r
-       FromFEN(iniPos + 4); // in XQ iniPos always has just "fen " prefix\r
+       FromFEN(iniPos + 13); // FEN part\r
        for(i=0; i<nr; i++) {\r
            int from=Sqr(move[i], 0), to=Sqr(move[i], 2);\r
            if(board[to] || (board[from]|32)  == 'p' && move[i][1] != move[i][3]) last = i;\r
@@ -154,19 +161,18 @@ StartSearch(char *ponder)
        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((inc || !mps && !sTime && sc == 'x') && !*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 = 1;\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
-       Sync(PAUSE); // wait for engine to acknowledge 'stop' with 'bestmove'.\r
 }\r
 \r
 void\r
@@ -176,7 +182,7 @@ LoadPos(int moveNr)
        if(sc == 'x') { // UCCI: send only reversible moves\r
            lastCapt = Play(moveNr); // find last capture (returns -1 if none!)\r
            Play(++lastCapt);        // reconstruct board after last capture\r
-           stm = (!strstr(iniPos+4, " b ") ^ lastCapt & 1 ? 'w' :  'b');\r
+           stm = (!strstr(iniPos+13, " 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
        EPRINT((f, "# %s moves", pos))\r
@@ -189,7 +195,8 @@ StartPonder(int moveNr)
 {\r
        if(!move[moveNr][0]) return; // no ponder move\r
        LoadPos(moveNr+1);\r
-       pondering = 1; lastDepth = 1;\r
+       searching = 1; lastDepth = 1;\r
+       DPRINT("# ponder on %s\n", move[moveNr]);\r
        StartSearch(" ponder");\r
 }\r
 \r
@@ -199,17 +206,6 @@ Analyze(char *val)
     if(*anaOpt) EPRINT((f, "# setoption %s%s %s%s\n", nameWord, anaOpt, valueWord, val));\r
 }\r
 \r
-int\r
-Release()\r
-{   // send setoption commands backlogged during thinking to engine, aborting ponder or analysis search if necessary\r
-    int len = logLen - sentLen, analyse = searching;\r
-    if(len <= 0) return 0;\r
-    StopPonder(pondering | searching); pondering = searching = 0; // force new search if settings change during analysis (multi-PV!)\r
-    fwrite(backLog + sentLen, 1, len, toE); sentLen += len; DPRINT("# release %d\n", len);\r
-    if(ponder && computer == 1 - stm) StartPonder(moveNr); // (re)start ponder search\r
-    return analyse; // return 1 if analysis search should be restarted\r
-}\r
-\r
 char *Convert(char *pv)\r
 {   // convert Shogi coordinates to WB\r
     char *p, *q, c;\r
@@ -217,7 +213,7 @@ char *Convert(char *pv)
     if(sc != 's') return pv;\r
     p = pv; q = buf;\r
     while(c = *p++) {\r
-        if(c >= '0' && c <= '9' || c >= 'a' && c <= 'z') *q++ = 'a'+'0'+size - c; else *q++ = c;\r
+        if(c >= '0' && c <= '9' || c >= 'a' && c <= 'z') *q++ = 'a'+'0' + (c >= 'a' ? size : hsize) - c; else *q++ = c;\r
     }\r
     *q++ = 0;\r
     return buf;\r
@@ -228,12 +224,12 @@ Move4GUI(char *m)
 {\r
     if(sc == 's') {\r
       // convert USI move to WB format\r
-      m[2] = 'a'+'0'+size - m[2];\r
+      m[2] = 'a'+'0'+hsize - m[2];\r
       m[3] = 'a'+'0'+size - m[3];\r
       if(m[1] == '*') { // drop\r
        m[1] = '@';\r
       } else {\r
-       m[0] = 'a'+'0'+size - m[0];\r
+       m[0] = 'a'+'0'+hsize - m[0];\r
        m[1] = 'a'+'0'+size - m[1];\r
        if((stm == WHITE ? (m[1]>'0'+size-size/3 || m[3]>'0'+size-size/3)\r
                                 : (m[1] <= '0'+size/3 || m[3] <= '0'+size/3)) && m[4] != '+')\r
@@ -243,10 +239,10 @@ Move4GUI(char *m)
 }\r
 \r
 int\r
-ReadLine (FILE *f, char *line)\r
+ReadLine (FILE *f, char *line, int len)\r
 {\r
     int x, i = 0;\r
-    while((x = fgetc(f)) != EOF && (line[i] = x) != '\n') i++; line[++i] = 0;\r
+    while((x = fgetc(f)) != EOF && (line[i] = x) != '\n') i+=(i<len); line[++i] = 0;\r
     return (x != EOF);\r
 }\r
 \r
@@ -256,16 +252,16 @@ HandleEngineOutput()
     char line[1024], command[256]; static char egts[999];\r
 \r
     while(1) {\r
-       int i=0, x; char *p, dummy, len;\r
+       int i=0; char *p, *q, dummy;\r
 \r
        fflush(stdout); fflush(toE);\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
+       if(fromF && !ReadLine(fromF, line, 1022))  fromF = 0, printf("# end fake\n");\r
+       if(!fromF && !ReadLine(fromE, line, 1022)) 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 == 1) { 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
@@ -273,24 +269,24 @@ HandleEngineOutput()
            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
-           Release(); // send setoption commands that arrived during search\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(moveNr);\r
-             }\r
+             if(computer != NONE && ponder) StartPonder(moveNr);\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(pause) { pause = 0; Sync(WAKEUP); } // release commands that came in during think\r
+           if((q = strchr(line+9, ','))) { // multi-leg move\r
+             *q++ = 0; Move4GUI(line+9);   // split\r
+             printf("move %s,\n", line+9); // send first leg\r
+            } else q = line + 9;\r
+           Move4GUI(q);\r
+           printf("move %s\n", q); // send move to GUI\r
+            if(p) Move4GUI(p+7), printf("Hint: %s\n", p+7);\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=(GetTickCount() - startTime)/10, n=1;\r
@@ -308,17 +304,6 @@ HandleEngineOutput()
                }\r
                continue;\r
            }\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
-               }\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
                if(p = strstr(line+4, " depth "))      sscanf(p+7, "%d", &d), statDepth = d;\r
@@ -327,8 +312,6 @@ HandleEngineOutput()
                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(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
@@ -338,6 +321,18 @@ HandleEngineOutput()
                    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
@@ -357,7 +352,7 @@ HandleEngineOutput()
            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
-               memory = oldMem = atoi(val); hasHash = 1\r
+               memory = oldMem = atoi(val); hasHash = max\r
                strcpy(hashOpt, name);\r
                continue;\r
            }\r
@@ -386,6 +381,7 @@ HandleEngineOutput()
                    sprintf(buf + strlen(buf), "%s%s%s", min++ ? " /// " : " ", strcmp(type, val) ? "" : "*", val);\r
                }\r
                strcat(q, "\"\n");\r
+\r
            }\r
            else buf[0] = 0; // ignore unrecognized option types\r
            if(buf[0]) printf("%s", buf);\r
@@ -395,29 +391,24 @@ HandleEngineOutput()
            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
+           char *p = varList, *q = p;\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
+           *p = 0;\r
            if(frc) sprintf(p, ",normal,fischerandom"), printf("feature oocastle=%d\n", frc<0); // unannounced FRC uses O-O castling\r
-           if(*varList) printf("feature variants=\"%s\"\n", varList+1); // from UCI_Variant combo and/or UCI_Chess960 check options\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
+           printf("feature smp=1 memory=%d done=1\n", hasHash > 0);\r
            if(unit == 2) { unit = 1; EPRINT((f, "# setoption usemillisec true\n")) }\r
-           Sync(WAKEUP); // done with options\r
+           fflush(stdout); return; // done with options\r
        }\r
     }\r
 }\r
 \r
-void *\r
-Engine2GUI()\r
-{\r
-    if(fromF = fopen("DefectiveEngineOptions.ini", "r")) printf("# fake engine input\n");\r
-    HandleEngineOutput();\r
-}\r
-\r
 void\r
 Move4Engine(char *m)\r
 {\r
@@ -426,28 +417,28 @@ Move4Engine(char *m)
       if(m[1] == '@') { // drop\r
        m[1] = '*';\r
       } else {\r
-       m[0] = 'a'+'0'+size - m[0];\r
+       m[0] = 'a'+'0'+hsize - m[0];\r
        m[1] = 'a'+'0'+size - m[1];\r
       }\r
-      m[2] = 'a'+'0'+size - m[2];\r
+      m[2] = 'a'+'0'+hsize - m[2];\r
       m[3] = 'a'+'0'+size - m[3];\r
       if(m[4] == '=') m[4] = 0; // no '=' in USI format!\r
       else if(m[4]) m[4] = '+'; // cater to WB 4.4 bug :-(\r
     }\r
 }\r
 \r
-int DoCommand (char *line);\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;\r
+    int i;\r
 \r
-    while(1) {\r
-       int i, difficult, think=0;\r
+    if(suspended || searching) return;\r
 \r
-       if((computer == stm || computer == ANALYZE && !searching) && !suspended) {\r
+       if(computer == stm || computer == ANALYZE && sm != 1) {\r
            DPRINT("# start search\n");\r
            LoadPos(moveNr); fflush(stdout); // load position\r
            // and set engine thinking (note USI swaps colors!)\r
@@ -458,26 +449,46 @@ GUI2Engine()
                    EPRINT((f, " searchmoves"))\r
                    for(i=1; i<nr; i++) if(on[i]) EPRINT((f, " %s", moveMap[i]))\r
                }\r
-               EPRINT((f, "\n")) searching = 1; // suppresses spurious commands during analysis starting new searches\r
-           } else pause = think = 2, StartSearch(""); // request suspending of input processing while thinking\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
-      nomove:\r
+       else if(BLACK+WHITE-stm == computer && ponder && moveNr) StartPonder(moveNr);\r
+}\r
+\r
+void\r
+GUI2Engine()\r
+{\r
+    char line[256], command[256], *p;\r
+\r
+    while(1) {\r
+       int 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
-       if(!ReadLine(stdin, line)) printf("# EOF\n"), sprintf(line, "quit -1\n");\r
-       if(think && !pause) Sync(PAUSE), think = 0, Release(); // if no longer thinking, take dummy pause\r
-       sscanf(line, "%s", command); DPRINT("# '%s' think=%d pause=%d log=%d sent=%d\n", command, think, pause, logLen, sentLen);\r
+       if(!ReadLine(stdin, line, 254)) printf("# EOF\n"), sprintf(line, "quit -1\n");\r
+       if(!sscanf(line, "%s", command)) return;\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, "draw"))   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 + pondering; // remember if we were pondering, and stop search ignoring bestmove\r
-           StopPonder(pondering || computer == stm);\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
@@ -486,19 +497,11 @@ GUI2Engine()
            if(*canPonder) ponder = 1, sprintf(command, "option"), sprintf(line, "option %s=1\n", canPonder); else continue;\r
          }\r
          if(!strcmp(command, "option")) {\r
-           char *p;\r
-           if(logLen == sentLen) logLen = 0, sentLen = 0; // engine is up to date; reset buffer\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
-           if(p = strchr(line, '=')) {\r
-               *p++ = 0;\r
-               if(strstr(checkOptions, line+7)) sprintf(p, "%s\n", atoi(p) ? "true" : "false");\r
-               snprintf(backLog+logLen, 9999-logLen, "setoption %s%s %s%s", nameWord, line+7, valueWord, p);\r
-           } else snprintf(backLog+logLen, 9999-logLen, "setoption %s%s\n", nameWord, line+7);\r
-           DPRINT("# backlog: %s", backLog+logLen); logLen += strlen(backLog+logLen);\r
-           if(!think && Release()) break; // break will restart analysis; pondering is restarted by Release itself\r
+           difficult = 1;\r
          }\r
          else difficult = 1; // difficult command; terminate loop for easy ones\r
        }\r
@@ -508,73 +511,94 @@ GUI2Engine()
        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
+           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
-                   char *draw = drawOffer ? " draw" : ""; drawOffer = 0;\r
-                   pondering = 0; pause = 2; moveNr++; startTime = GetTickCount(); // clock starts running now\r
-                   EPRINT((f, "# ponderhit%s\n", draw)) fflush(toE); fflush(stdout);\r
-                   think = 2; // request blocking input during thinking\r
-                   goto nomove;\r
-               }\r
-               StopPonder(1); searching = 0;\r
+           if(searching == 1 && !strcmp(command, move[moveNr])) { // ponder hit\r
+               char *draw = drawOffer ? " draw" : ""; drawOffer = 0;\r
+               stm = WHITE+BLACK - stm;         // for acceptance of ponder move (can be safely done out of sync)\r
+               searching = 3; moveNr++; startTime = GetTickCount(); // clock starts running now\r
+               EPRINT((f, "# ponderhit%s\n", draw)) fflush(toE); fflush(stdout);\r
+           } else {\r
+               if(searching) StopSearch(1);     // ponder miss or analysis, as moves won't arrive during thinking\r
+               p = command; *qEnd++ = 'e'; *qEnd++ = ' '; while(qEnd < queue+10000 && (*qEnd++ = *p++)) {} *qEnd++ = '\n';\r
+               Sync(WAKEUP);                    // queue move for adding it to game (and toggle stm)\r
            }\r
-           strcpy(move[moveNr++], command); // possibly overwrites ponder move\r
-           continue;\r
-       }\r
+       } else\r
        if(!strcmp(command, "resume")) {\r
            if(suspended == 2) StartPonder(moveNr); // restart interrupted ponder search\r
-           suspended = think = 0; continue;  // causes thinking to start in normal way if on move or analyzing\r
-       }\r
-       if(think) { // command arrived during thinking; order abort for 'instant commands'\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")) { EPRINT((f, "# stop\n")); fflush(toE); }\r
-           Sync(PAUSE); Release(); // block processing of difficult commands during thinking; send backlog left because of race\r
-       }\r
-       if(DoCommand(line)) goto nomove;\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
+       // when 'stop' doesn't catch engine's attention in reasonable time, so the GUI might kill us:\r
+       if(!strcmp(command, "quit")) { Bury(killDelay); exit(0); } // kill the engine and exit\r
+      }\r
     }\r
 }\r
 \r
-int\r
-DoCommand (char *line)\r
+void\r
+IsReady ()\r
+{\r
+    EPRINT((f, "# isready\n")) fflush(toE);\r
+    HandleEngineOutput(); // wait for readyok\r
+}\r
+\r
+void\r
+DoCommand ()\r
 {\r
-    char command[256], *p, *q, *r, type[99];\r
+    char line[1024], command[256], *p, *q, *r, type[99], c;\r
     int i;\r
 \r
-    sscanf(line, "%s", command);\r
+    p=line; while(qStart < qEnd && (*p++ = *qStart++) != '\n') {} *p = 0;\r
+    sscanf(line, "%s %s", command, type); 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(newCnt++) return; // prevent a 2nd 'isready' due to reuse=0-violating 'new' preceding 'quit'\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 && strstr(varList, ",normal")) EPRINT((f, "# setoption name UCI_Variant value chess\n"))\r
+           IsReady();\r
            if(sc == 'x') { if(newGame) EPRINT((f, "# setoption newgame\n")) } else // optional in UCCI\r
-           if(varOpt) EPRINT((f, "# setoption name UCI_Variant value chess\n"))\r
-           pause = 1; // wait for option settings to take effect\r
-           EPRINT((f, "# isready\n")) fflush(toE);\r
-           Sync(PAUSE); // wait for readyok\r
-           EPRINT((f, "# u%cinewgame\n", sc)) fflush(toE);\r
+               { EPRINT((f, "# u%cinewgame\n", sc)) fflush(toE); if(sc != 's') IsReady(); } // avoid isready in USI\r
+       }\r
+        else if(!strcmp(command, "e")) { strcpy(move[moveNr++], type); stm ^= WHITE|BLACK; return; }\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
-           sscanf(line, "level %d %d:%d %d", &mps, &tc, &sec, &inc) == 4 ||\r
-           sscanf(line, "level %d %d %d", &mps, &tc, &inc);\r
+           if(sscanf(line, "level %d %d:%d %d", &mps, &tc, &sec, &inc) != 4)\r
+               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, "protover")) {\r
-           if(!varList[0]) strcpy(varList, sc=='s' ? ",shogi,5x5+5_shogi" : 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
            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
-           Sync(PAUSE); // wait for uciok\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, '[')) && !varOpt) { char c;\r
+                if((p = strchr(line+9, '[')) && !varOpt) {\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
@@ -587,35 +611,27 @@ DoCommand (char *line)
        else if(!strcmp(command, "variant")) {\r
                if(varOpt) {\r
                    EPRINT((f, "# setoption name UCI_Variant value %sucinewgame\nisready\n", line+8))\r
-                   fflush(toE); Sync(PAUSE);\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
+               c = 0; if(sscanf(line+8, "%dx%d+%d_shogi%c", &hsize, &size, &i, &c) && c == '\n') strcpy(iniPos, "position startpos");\r
+               if(!strcmp(line+8, "shogi\n")) hsize = size = 9, strcpy(iniPos, "position startpos");\r
+               if(!strcmp(line+8, "xiangqi\n")) sprintf(iniPos, "%s %c", XQPOS+9*(sc2 == 'c'), sc2 == 'c' ? 'r' : 'w'); // with -c use Cyclone dialect\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), searching = 0;\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
-           return 1;\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)) return 1; // no moves enabled; continue current search\r
-           if(computer == ANALYZE) StopPonder(1), searching = 0; // abort old analysis\r
        }\r
-       else if(!strcmp(command, "xboard")) ;\r
        else if(!strcmp(command, "analyze"))computer = ANALYZE, collect = 1, sm = 0, Analyze("true");\r
-       else if(!strcmp(command, "exit"))   computer = NONE, StopPonder(1), searching = 0, Analyze("false");\r
-       else if(!strcmp(command, "force"))  computer = NONE, StopPonder(pondering);\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, "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, "memory")) { sscanf(line, "memory %d", &memory); if(memory > hasHash) memory = hasHash; }\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
@@ -625,14 +641,26 @@ DoCommand (char *line)
        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, "name"))   { if(namOpt) EPRINT((f, "# setoption name UCI_Opponent value none none %s %s", comp ? "computer" : "human", line+5)) }\r
-       else if(!strcmp(command, "computer")) comp = 1;\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 if(!strcmp(command, "quit"))   { EPRINT((f, "# quit\n")) fflush(toE); }\r
+       else printf("Error (unknown command): %s\n", command);\r
 \r
-    return 0;\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
 int\r
@@ -679,9 +707,9 @@ StartEngine(char *cmdLine, char *dir)
 \r
   if (! fSuccess) return GetLastError();\r
 \r
-//  if (0) { // in the future we could trigger this by an argument\r
-//    SetPriorityClass(piProcInfo.hProcess, GetWin32Priority(appData.niceEngines));\r
-//  }\r
+  if (priority > 0) { // for now only implement all lowered priorityies the same way\r
+    SetPriorityClass(piProcInfo.hProcess, BELOW_NORMAL_PRIORITY_CLASS);\r
+  }\r
 \r
   /* Close the handles we don't need in the parent */\r
   CloseHandle(piProcInfo.hThread);\r
@@ -689,7 +717,6 @@ StartEngine(char *cmdLine, char *dir)
   CloseHandle(hChildStdoutWr);\r
 \r
   process = piProcInfo.hProcess;\r
-  pid = piProcInfo.dwProcessId;\r
   fromE = (FILE*) _fdopen( _open_osfhandle((long)hChildStdoutRd, _O_TEXT|_O_RDONLY), "r");\r
   toE   = (FILE*) _fdopen( _open_osfhandle((long)hChildStdinWr, _O_WRONLY), "w");\r
 #else\r
@@ -697,7 +724,8 @@ StartEngine(char *cmdLine, char *dir)
     int i, toEngine[2], fromEngine[2];\r
 \r
     if (dir && dir[0] && chdir(dir)) { perror(dir); exit(1); }\r
-    pipe(toEngine); pipe(fromEngine); // create two pipes\r
+    i = pipe(toEngine) + pipe(fromEngine); // create two pipes\r
+    if(i < 0) printf("tellusererror UCI2WB: no engine pipe\n"), exit(0);\r
 \r
     if ((pid = fork()) == 0) { // Child\r
        dup2(toEngine[0], 0);   close(toEngine[0]);   close(toEngine[1]);   // stdin from toE pipe\r
@@ -707,6 +735,7 @@ StartEngine(char *cmdLine, char *dir)
        strcpy(buf, cmdLine); p = buf;\r
        for (i=0;;) { argv[i++] = p; p = strchr(p, ' '); if (p == NULL) break; *p++ = 0; }\r
        argv[i] = NULL;\r
+        if(priority) i = nice(priority);\r
         execvp(argv[0], argv); // startup engine\r
        \r
        perror(argv[0]); exit(1); // could not start engine; quit.\r
@@ -720,22 +749,25 @@ StartEngine(char *cmdLine, char *dir)
   return NO_ERROR;\r
 }\r
 \r
+int\r
 main(int argc, char **argv)\r
 {\r
-       char *dir = NULL, *p, *q; int e;\r
+       char *dir = NULL;\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")) { strcpy(varList+1, argv[2]); *varList = ','; argc-=2; argv+=2; }\r
+       if(argc > 2 && !strcmp(argv[1], "-nice")) { sscanf(argv[2], "%d", &priority); argc-=2; argv+=2; }\r
+       if(argc > 2 && !strcmp(argv[1], "-kill")) { sscanf(argv[2], "%d", &killDelay); 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) { printf("usage is: %s [debug] [-s|-x|-c|-f] <engine.exe> [<engine directory>]\n", argv[0]); exit(-1); }\r
        if(argc > 2) dir = argv[2];\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
+       else if(sc != 's') sc2 = sc, sc = 'c';    // UCI for normal Chess\r
 \r
        // spawn engine proc\r
        if(StartEngine(binary = argv[1], dir) != NO_ERROR) { perror(argv[1]), exit(-1); }\r
@@ -751,4 +783,5 @@ main(int argc, char **argv)
 \r
        // handle GUI->engine traffic in original thread\r
        GUI2Engine();\r
+       return 0;\r
 }\r