security fix: replaced sprintf with snprintf
authorArun Persaud <arun@nubati.net>
Mon, 13 Sep 2010 03:04:03 +0000 (20:04 -0700)
committerArun Persaud <arun@nubati.net>
Fri, 8 Oct 2010 01:46:48 +0000 (18:46 -0700)
replaced most sprintf with snprintf. There are still some left where for example a pointer is used and is allocated in the line before, which should be fine... and some others.

18 files changed:
args.h
backend.c
childio.c
engineoutput.c
gamelist.c
pgntags.c
pixmaps/convert.c
winboard/help.c
winboard/jaws.c
winboard/wchat.c
winboard/wgamelist.c
winboard/winboard.c
winboard/woptions.c
winboard/wsettings.c
xboard.c
xoptions.c
zic2xpm.c
zippy.c

diff --git a/args.h b/args.h
index 9d3530f..00126f9 100644 (file)
--- a/args.h
+++ b/args.h
@@ -2,7 +2,7 @@
  * args.c -- Option parsing and saving for X and Windows versions of XBoard
  *
  * Copyright 1991 by Digital Equipment Corporation, Maynard,
- * Massachusetts. 
+ * Massachusetts.
  *
  * Enhancements Copyright 1992-2001, 2002, 2003, 2004, 2005, 2006,
  * 2007, 2008, 2009, 2010 Free Software Foundation, Inc.
  * along with this program. If not, see http://www.gnu.org/licenses/.  *
  *
  *------------------------------------------------------------------------
- ** See the file ChangeLog for a revision history.  
+ ** See the file ChangeLog for a revision history.
 */
 
 // Note: this file is not a normal header, but contains executable code
 // for #inclusion in winboard.c and xboard.c, rather than separate compilation,
-// so that it can make use of the proper context of #defined symbols and 
+// so that it can make use of the proper context of #defined symbols and
 // declarations in those files.
 
 typedef enum {
-  ArgString, ArgInt, ArgFloat, ArgBoolean, ArgTrue, ArgFalse, ArgNone, 
+  ArgString, ArgInt, ArgFloat, ArgBoolean, ArgTrue, ArgFalse, ArgNone,
   ArgColor, ArgAttribs, ArgFilename, ArgBoardSize, ArgFont, ArgCommSettings,
   ArgSettingsFilename,
   ArgX, ArgY, ArgZ // [HGM] placement: for window-placement options stored relative to main window
@@ -129,7 +129,7 @@ typedef char GetFunc(void *getClosure);
 void ParseArgs(GetFunc get, void *cl);
 
 // [HGM] this is an exact duplicate of something in winboard.c. Move to backend.c?
-char *defaultTextAttribs[] = 
+char *defaultTextAttribs[] =
 {
   COLOR_SHOUT, COLOR_SSHOUT, COLOR_CHANNEL1, COLOR_CHANNEL, COLOR_KIBITZ,
   COLOR_TELL, COLOR_CHALLENGE, COLOR_REQUEST, COLOR_SEEK, COLOR_NORMAL,
@@ -238,7 +238,7 @@ ArgDescriptor argDescriptors[] = {
   { "xtelnet", ArgFalse, (void *) &appData.useTelnet, FALSE, INVALID },
   { "-telnet", ArgFalse, (void *) &appData.useTelnet, FALSE, INVALID },
   { "telnetProgram", ArgFilename, (void *) &appData.telnetProgram, FALSE, (ArgIniType) TELNET_PROGRAM },
-  { "internetChessserverHelper", ArgFilename, (void *) &appData.icsHelper, 
+  { "internetChessserverHelper", ArgFilename, (void *) &appData.icsHelper,
        FALSE, INVALID }, // for XB
   { "icshelper", ArgFilename, (void *) &appData.icsHelper, FALSE, (ArgIniType) "" },
   { "seekGraph", ArgBoolean, (void *) &appData.seekGraph, TRUE, (ArgIniType) FALSE },
@@ -307,7 +307,7 @@ ArgDescriptor argDescriptors[] = {
   { "popup", ArgTrue, (void *) &appData.popupMoveErrors, FALSE, INVALID },
   { "xpopup", ArgFalse, (void *) &appData.popupMoveErrors, FALSE, INVALID },
   { "-popup", ArgFalse, (void *) &appData.popupMoveErrors, FALSE, INVALID },
-  { "popUpErrors", ArgBoolean, (void *) &appData.popupMoveErrors, 
+  { "popUpErrors", ArgBoolean, (void *) &appData.popupMoveErrors,
     FALSE, INVALID }, /* only so that old WinBoard.ini files from betas can be read */
   { "clockFont", ArgFont, (void *) CLOCK_FONT, TRUE, INVALID },
   { "messageFont", ArgFont, (void *) MESSAGE_FONT, !XBOARD, INVALID },
@@ -540,9 +540,9 @@ ArgDescriptor argDescriptors[] = {
   { "polyglotDir", ArgFilename, (void *) &appData.polyglotDir, TRUE, (ArgIniType) "" },
   { "usePolyglotBook", ArgBoolean, (void *) &appData.usePolyglotBook, TRUE, (ArgIniType) FALSE },
   { "polyglotBook", ArgFilename, (void *) &appData.polyglotBook, TRUE, (ArgIniType) "" },
-  { "bookDepth", ArgInt, (void *) &appData.bookDepth, TRUE, (ArgIniType) 12 }, 
-  { "bookVariation", ArgInt, (void *) &appData.bookStrength, TRUE, (ArgIniType) 50 }, 
-  { "defaultHashSize", ArgInt, (void *) &appData.defaultHashSize, TRUE, (ArgIniType) 64 }, 
+  { "bookDepth", ArgInt, (void *) &appData.bookDepth, TRUE, (ArgIniType) 12 },
+  { "bookVariation", ArgInt, (void *) &appData.bookStrength, TRUE, (ArgIniType) 50 },
+  { "defaultHashSize", ArgInt, (void *) &appData.defaultHashSize, TRUE, (ArgIniType) 64 },
   { "defaultCacheSizeEGTB", ArgInt, (void *) &appData.defaultCacheSizeEGTB, TRUE, (ArgIniType) 4 },
   { "defaultPathEGTB", ArgFilename, (void *) &appData.defaultPathEGTB, TRUE, (ArgIniType) "c:\\egtb" },
   { "language", ArgFilename, (void *) &appData.language, TRUE, (ArgIniType) "" },
@@ -709,8 +709,12 @@ void
 ExitArgError(char *msg, char *badArg)
 {
   char buf[MSG_SIZ];
+  int len;
+
+  len = snprintf(buf,MSG_SIZ, "%s %s", msg, badArg);
+  if( (len > MSG_SIZ) && appData.debugMode )
+    fprintf(debugFP, "ExitArgError: buffer truncated. Input: msg=%s badArg=%s\n", msg, badArg);
 
-  sprintf(buf, "%s %s", msg, badArg);
   DisplayFatalError(buf, 0, 2);
   exit(2);
 }
@@ -751,13 +755,19 @@ Boolean
 ParseSettingsFile(char *name, char **addr)
 {
   FILE *f;
-  int ok; char buf[MSG_SIZ], fullname[MSG_SIZ];
+  int ok,len;
+  char buf[MSG_SIZ], fullname[MSG_SIZ];
+
 
   ok = MySearchPath(installDir, name, fullname);
-  if(!ok && strchr(name, '.') == NULL) { // [HGM] append default file-name extension '.ini' when needed
-    sprintf(buf, "%s.ini", name);
-    ok = MySearchPath(installDir, buf, fullname);
-  }
+  if(!ok && strchr(name, '.') == NULL)
+    { // append default file-name extension '.ini' when needed
+      len = snprintf(buf,MSG_SIZ, "%s.ini", name);
+      if( (len > MSG_SIZ) && appData.debugMode )
+       fprintf(debugFP, "ParseSettingsFile: buffer truncated. Input: name=%s \n",name);
+
+      ok = MySearchPath(installDir, buf, fullname);
+    }
   if (ok) {
     f = fopen(fullname, "r");
     if (f != NULL) {
@@ -843,7 +853,7 @@ ParseArgs(GetFunc get, void *cl)
        case NULLCHAR:
          start = NULLCHAR;
          break;
-         
+
        case '}':
          ch = get(cl);
          start = NULLCHAR;
@@ -854,7 +864,7 @@ ParseArgs(GetFunc get, void *cl)
          ch = get(cl);
          break;
        }
-      }          
+      }
     } else if (ch == '\'' || ch == '"') {
       // Quoting with ' ' or " ", with \ as escape character.
       // Inconvenient for long strings that may contain Windows filenames.
@@ -947,7 +957,7 @@ ParseArgs(GetFunc get, void *cl)
       break;
 
     case ArgX:
-      *(int *) ad->argLoc = ValidateInt(argValue) + wpMain.x; // [HGM] placement: translate stored relative to absolute 
+      *(int *) ad->argLoc = ValidateInt(argValue) + wpMain.x; // [HGM] placement: translate stored relative to absolute
       break;
 
     case ArgY:
@@ -956,7 +966,7 @@ ParseArgs(GetFunc get, void *cl)
 
     case ArgZ:
       *(int *) ad->argLoc = ValidateInt(argValue);
-      EnsureOnScreen(&wpMain.x, &wpMain.y, minX, minY); 
+      EnsureOnScreen(&wpMain.x, &wpMain.y, minX, minY);
       break;
 
     case ArgFloat:
@@ -1005,7 +1015,7 @@ ParseArgs(GetFunc get, void *cl)
        ParseTextAttribs(cc, argValue); // [HGM] wrapper for platform independency
       }
       break;
-      
+
     case ArgBoardSize:
       ParseBoardSize(ad->argLoc, argValue);
       break;
@@ -1084,7 +1094,7 @@ ParseIcsTextMenu(char *icsTextMenuString)
       p = t + 1;
     }
     e++;
-  } 
+  }
 }
 
 void
@@ -1175,22 +1185,34 @@ InitAppData(char *lpCmdLine)
       char *p = StrStr(appData.firstChessProgram, "WBopt");
       static char *f = "first";
       char buf[MSG_SIZ], *q = buf;
-      if(p != NULL) { // engine command line contains WinBoard options
-          sprintf(buf, p+6, f, f, f, f, f, f, f, f, f, f); // replace %s in them by "first"
+      int len;
+
+      if(p != NULL)
+       { // engine command line contains WinBoard options
+          len = snprintf(buf, MSG_SIZ, p+6, f, f, f, f, f, f, f, f, f, f); // replace %s in them by "first"
+         if( (len > MSG_SIZ) && appData.debugMode )
+           fprintf(debugFP, "InitAppData: buffer truncated.\n");
+
           ParseArgs(StringGet, &q);
           p[-1] = 0; // cut them offengine command line
-      }
+       }
   }
   // now do same for second chess program
   if(appData.secondChessProgram != NULL) {
       char *p = StrStr(appData.secondChessProgram, "WBopt");
       static char *s = "second";
       char buf[MSG_SIZ], *q = buf;
-      if(p != NULL) { // engine command line contains WinBoard options
-          sprintf(buf, p+6, s, s, s, s, s, s, s, s, s, s); // replace %s in them by "first"
+      int len;
+
+      if(p != NULL)
+       { // engine command line contains WinBoard options
+          len = snprintf(buf,MSG_SIZ, p+6, s, s, s, s, s, s, s, s, s, s); // replace %s in them by "first"
+         if( (len > MSG_SIZ) && appData.debugMode )
+           fprintf(debugFP, "InitAppData: buffer truncated.\n");
+
           ParseArgs(StringGet, &q);
           p[-1] = 0; // cut them offengine command line
-      }
+       }
   }
 
   /* Propagate options that affect others */
@@ -1203,7 +1225,7 @@ InitAppData(char *lpCmdLine)
   if ((!appData.noChessProgram && !chessProgram && !appData.icsActive) ||
       (appData.icsActive && *appData.icsHost == NULLCHAR) ||
       (chessProgram && (*appData.firstChessProgram == NULLCHAR ||
-                        *appData.secondChessProgram == NULLCHAR))) 
+                        *appData.secondChessProgram == NULLCHAR)))
                PopUpStartupDialog();
 
   /* Make sure save files land in the right (?) directory */
@@ -1325,7 +1347,7 @@ SaveSettings(char* name)
       fprintf(f, OPTCHAR "%s" SEPCHAR "%g\n", ad->argName, *(float *)ad->argLoc);
       break;
     case ArgBoolean:
-      fprintf(f, OPTCHAR "%s" SEPCHAR "%s\n", ad->argName, 
+      fprintf(f, OPTCHAR "%s" SEPCHAR "%s\n", ad->argName,
        (*(Boolean *)ad->argLoc) ? "true" : "false");
       break;
     case ArgTrue:
@@ -1368,6 +1390,7 @@ GetArgValue(char *name)
 { // retrieve (as text) current value of string or int argument given by name
   // (this is used for maing the values available in the adapter command)
   ArgDescriptor *ad;
+  int len;
 
   for (ad = argDescriptors; ad->argName != NULL; ad++)
     if (strcmp(ad->argName, name) == 0) break;
@@ -1378,12 +1401,19 @@ GetArgValue(char *name)
     case ArgString:
     case ArgFilename:
       strncpy(name, *(char**) ad->argLoc, MSG_SIZ);
+
       return TRUE;
     case ArgInt:
-      sprintf(name, "%d", *(int*) ad->argLoc);
+      len = snprintf(name, MSG_SIZ, "%d", *(int*) ad->argLoc);
+      if( (len > MSG_SIZ) && appData.debugMode )
+       fprintf(debugFP, "GetArgValue: buffer truncated.\n");
+
       return TRUE;
     case ArgBoolean:
-      sprintf(name, "%s", *(Boolean*) ad->argLoc ? "true" : "false");
+      len = snprintf(name, MSG_SIZ, "%s", *(Boolean*) ad->argLoc ? "true" : "false");
+      if( (len > MSG_SIZ) && appData.debugMode )
+       fprintf(debugFP, "GetArgValue: buffer truncated.\n");
+
       return TRUE;
     default: ;
   }
index 4eaa5b1..67a1c1a 100644 (file)
--- a/backend.c
+++ b/backend.c
@@ -315,7 +315,6 @@ safeStrCpy( char *dst, const char *src, size_t count )
   /* see for example: https://buildsecurityin.us-cert.gov/bsi-rules/home/g1/854-BSI.html
    *
    * usage:   safeStrCpy( stringA, stringB, sizeof(stringA)/sizeof(stringA[0]);
-   *
    */
 
   assert( dst != NULL );
@@ -825,25 +824,41 @@ InitBackEnd1()
     first.hasOwnBookUCI = appData.firstHasOwnBookUCI; /* [AS] */
     second.hasOwnBookUCI = appData.secondHasOwnBookUCI; /* [AS] */
 
-    if (appData.firstProtocolVersion > PROTOVER ||
-       appData.firstProtocolVersion < 1) {
-      char buf[MSG_SIZ];
-      sprintf(buf, _("protocol version %d not supported"),
-             appData.firstProtocolVersion);
-      DisplayFatalError(buf, 0, 2);
-    } else {
-      first.protocolVersion = appData.firstProtocolVersion;
-    }
+    if (appData.firstProtocolVersion > PROTOVER
+       || appData.firstProtocolVersion < 1)
+      {
+       char buf[MSG_SIZ];
+       int len;
 
-    if (appData.secondProtocolVersion > PROTOVER ||
-       appData.secondProtocolVersion < 1) {
-      char buf[MSG_SIZ];
-      sprintf(buf, _("protocol version %d not supported"),
-             appData.secondProtocolVersion);
-      DisplayFatalError(buf, 0, 2);
-    } else {
-      second.protocolVersion = appData.secondProtocolVersion;
-    }
+       len = snprintf(buf, MSG_SIZ, _("protocol version %d not supported"),
+                      appData.firstProtocolVersion);
+       if( (len > MSG_SIZ) && appData.debugMode )
+         fprintf(debugFP, "InitBackEnd1: buffer truncated.\n");
+
+       DisplayFatalError(buf, 0, 2);
+      }
+    else
+      {
+       first.protocolVersion = appData.firstProtocolVersion;
+      }
+
+    if (appData.secondProtocolVersion > PROTOVER
+       || appData.secondProtocolVersion < 1)
+      {
+       char buf[MSG_SIZ];
+       int len;
+
+       len = snprintf(buf, MSG_SIZ, _("protocol version %d not supported"),
+                      appData.secondProtocolVersion);
+       if( (len > MSG_SIZ) && appData.debugMode )
+         fprintf(debugFP, "InitBackEnd1: buffer truncated.\n");
+
+       DisplayFatalError(buf, 0, 2);
+      }
+    else
+      {
+       second.protocolVersion = appData.secondProtocolVersion;
+      }
 
     if (appData.icsActive) {
         appData.clockMode = TRUE;  /* changes dynamically in ICS mode */
@@ -874,6 +889,8 @@ InitBackEnd1()
 
     if (!appData.icsActive) {
       char buf[MSG_SIZ];
+      int len;
+
       /* Check for variants that are supported only in ICS mode,
          or not at all.  Some that are accepted here nevertheless
          have bugs; see comments below.
@@ -882,8 +899,11 @@ InitBackEnd1()
       switch (variant) {
       case VariantBughouse:     /* need four players and two boards */
       case VariantKriegspiel:   /* need to hide pieces and move details */
-      /* case VariantFischeRandom: (Fabien: moved below) */
-       sprintf(buf, _("Variant %s supported only in ICS mode"), appData.variant);
+       /* case VariantFischeRandom: (Fabien: moved below) */
+       len = snprintf(buf,MSG_SIZ, _("Variant %s supported only in ICS mode"), appData.variant);
+       if( (len > MSG_SIZ) && appData.debugMode )
+         fprintf(debugFP, "InitBackEnd1: buffer truncated.\n");
+
        DisplayFatalError(buf, 0, 2);
        return;
 
@@ -898,7 +918,10 @@ InitBackEnd1()
       case Variant35:
       case Variant36:
       default:
-       sprintf(buf, _("Unknown variant name %s"), appData.variant);
+       len = snprintf(buf, MSG_SIZ, _("Unknown variant name %s"), appData.variant);
+       if( (len > MSG_SIZ) && appData.debugMode )
+         fprintf(debugFP, "InitBackEnd1: buffer truncated.\n");
+
        DisplayFatalError(buf, 0, 2);
        return;
 
@@ -1049,18 +1072,22 @@ ParseTimeControl(tc, ti, mps)
   long tc2;
   char buf[MSG_SIZ], buf2[MSG_SIZ], *mytc = tc;
   int min, sec=0;
-  
+  int len;
+
   if(ti >= 0 && !strchr(tc, '+') && !strchr(tc, '/') ) mps = 0;
   if(!strchr(tc, '+') && !strchr(tc, '/') && sscanf(tc, "%d:%d", &min, &sec) >= 1)
       sprintf(mytc=buf2, "%d", 60*min+sec); // convert 'classical' min:sec tc string to seconds
   if(ti > 0) {
+
     if(mps)
-      sprintf(buf, ":%d/%s+%d", mps, mytc, ti);
-    else sprintf(buf, ":%s+%d", mytc, ti);
+      snprintf(buf, MSG_SIZ, ":%d/%s+%d", mps, mytc, ti);
+    else 
+      snprintf(buf, MSG_SIZ, ":%s+%d", mytc, ti);
   } else {
     if(mps)
-             sprintf(buf, ":%d/%s", mps, mytc);
-    else sprintf(buf, ":%s", mytc);
+      snprintf(buf, MSG_SIZ, ":%d/%s", mps, mytc);
+    else 
+      snprintf(buf, MSG_SIZ, ":%s", mytc);
   }
   fullTimeControlString = StrSave(buf); // this should now be in PGN format
   
@@ -1137,7 +1164,7 @@ InitBackEnd3 P((void))
 {
     GameMode initialMode;
     char buf[MSG_SIZ];
-    int err;
+    int err, len;
 
     InitChessProgram(&first, startedFromSetupPosition);
 
@@ -1153,14 +1180,18 @@ InitBackEnd3 P((void))
         ConsoleCreate();
 #endif
        err = establish();
-       if (err != 0) {
-           if (*appData.icsCommPort != NULLCHAR) {
-               sprintf(buf, _("Could not open comm port %s"),
-                       appData.icsCommPort);
-           } else {
-               snprintf(buf, sizeof(buf), _("Could not connect to host %s, port %s"),
+       if (err != 0)
+         {
+           if (*appData.icsCommPort != NULLCHAR)
+             len = snprintf(buf, MSG_SIZ, _("Could not open comm port %s"),
+                            appData.icsCommPort);
+           else
+             len = snprintf(buf, MSG_SIZ, _("Could not connect to host %s, port %s"),
                        appData.icsHost, appData.icsPort);
-           }
+
+           if( (len > MSG_SIZ) && appData.debugMode )
+             fprintf(debugFP, "InitBackEnd3: buffer truncated.\n");
+
            DisplayFatalError(buf, err, 1);
            return;
        }
@@ -1205,7 +1236,10 @@ InitBackEnd3 P((void))
     } else if (StrCaseCmp(appData.initialMode, "Training") == 0) {
       initialMode = Training;
     } else {
-      sprintf(buf, _("Unknown initialMode %s"), appData.initialMode);
+      len = snprintf(buf, MSG_SIZ, _("Unknown initialMode %s"), appData.initialMode);
+      if( (len > MSG_SIZ) && appData.debugMode )
+       fprintf(debugFP, "InitBackEnd3: buffer truncated.\n");
+
       DisplayFatalError(buf, 0, 2);
       return;
     }
@@ -1631,6 +1665,7 @@ StringToVariant(e)
     VariantClass v = VariantNormal;
     int i, found = FALSE;
     char buf[MSG_SIZ];
+    int len;
 
     if (!e) return v;
 
@@ -1806,7 +1841,10 @@ StringToVariant(e)
          v = VariantNormal;
          break;
        default:
-         sprintf(buf, _("Unknown wild type %d"), wnum);
+         len = snprintf(buf, MSG_SIZ, _("Unknown wild type %d"), wnum);
+         if( (len > MSG_SIZ) && appData.debugMode )
+           fprintf(debugFP, "StringToVariant: buffer truncated.\n");
+
          DisplayError(buf, 0);
          v = VariantUnknown;
          break;
@@ -1946,7 +1984,7 @@ TelnetRequest(ddww, option)
            break;
          default:
            ddwwStr = buf1;
-           sprintf(buf1, "%d", ddww);
+           snprintf(buf1,sizeof(buf1)/sizeof(buf1[0]), "%d", ddww);
            break;
        }
        switch (option) {
@@ -1955,7 +1993,7 @@ TelnetRequest(ddww, option)
            break;
          default:
            optionStr = buf2;
-           sprintf(buf2, "%d", option);
+           snprintf(buf2,sizeof(buf2)/sizeof(buf2[0]), "%d", option);
            break;
        }
        fprintf(debugFP, ">%s %s ", ddwwStr, optionStr);
@@ -2169,7 +2207,7 @@ AddAd(char *handle, char *rating, int base, int inc,  char rated, char *type, in
            if(v == VariantLoadable) type = "setup"; else
            type = VariantName(v);
        }
-       sprintf(buf, "%s (%s) %d %d %c %s%s", handle, rating, base, inc, rated, type, ext);
+       snprintf(buf, MSG_SIZ, "%s (%s) %d %d %c %s%s", handle, rating, base, inc, rated, type, ext);
        if(nrOfSeekAds < MAX_SEEK_ADS-1) {
            if(seekAdList[nrOfSeekAds]) free(seekAdList[nrOfSeekAds]);
            ratingList[nrOfSeekAds] = -1; // for if seeker has no rating
@@ -2251,7 +2289,7 @@ DrawSeekGraph()
        DrawSeekAxis(hMargin+5*(i%500==0), yy, hMargin-5, yy); // rating ticks
        if(i%500 == 0) {
            char buf[MSG_SIZ];
-           sprintf(buf, "%d", i);
+           snprintf(buf, MSG_SIZ, "%d", i);
            DrawSeekText(buf, hMargin+squareSize/8+7, yy);
        }
     }
@@ -2261,7 +2299,7 @@ DrawSeekGraph()
        DrawSeekAxis(xx, h-1-vMargin, xx, h-6-vMargin-3*(i%10==0)); // TC ticks
        if(i<=5 || (i>40 ? i%20 : i%10) == 0) {
            char buf[MSG_SIZ];
-           sprintf(buf, "%d", i);
+           snprintf(buf, MSG_SIZ, "%d", i);
            DrawSeekText(buf, xx-2-3*(i>9), h-1-vMargin/2);
        }
     }
@@ -2299,7 +2337,7 @@ int SeekGraphClick(ClickType click, int x, int y, int moving)
                return TRUE;
            } // on press 'hit', only show info
            if(moving == 2) return TRUE; // ignore right up-clicks on dot
-           sprintf(buf, "play %d\n", seekNrList[closest]);
+           snprintf(buf, MSG_SIZ, "play %d\n", seekNrList[closest]);
            SendToICS(ics_prefix);
            SendToICS(buf);
            return TRUE; // let incoming board of started game pop down the graph
@@ -2565,13 +2603,13 @@ read_from_ics(isr, closure, data, count, error)
 
            if (loggedOn && !intfSet) {
                if (ics_type == ICS_ICC) {
-                 sprintf(str,
+                 snprintf(str, MSG_SIZ,
                          "/set-quietly interface %s\n/set-quietly style 12\n",
                          programVersion);
                  if(appData.seekGraph && appData.autoRefresh) // [HGM] seekgraph
                      strcat(str, "/set-2 51 1\n/set seek 1\n");
                } else if (ics_type == ICS_CHESSNET) {
-                 sprintf(str, "/style 12\n");
+                 snprintf(str, MSG_SIZ, "/style 12\n");
                } else {
                  safeStrCpy(str, "alias $ @\n$set interface ", sizeof(str)/sizeof(str[0]));
                  strcat(str, programVersion);
@@ -2595,7 +2633,7 @@ read_from_ics(isr, closure, data, count, error)
                    parse[parse_pos] = NULLCHAR;
                    if(chattingPartner>=0) {
                        char mess[MSG_SIZ];
-                       sprintf(mess, "%s%s", talker, parse);
+                       snprintf(mess, MSG_SIZ, "%s%s", talker, parse);
                        OutputChatMessage(chattingPartner, mess);
                        chattingPartner = -1;
                        next_out = i+1; // [HGM] suppress printing in ICS window
@@ -2624,7 +2662,7 @@ read_from_ics(isr, closure, data, count, error)
                            OutputKibitz(suppressKibitz, parse);
                        } else {
                            char tmp[MSG_SIZ];
-                           sprintf(tmp, _("your opponent kibitzes: %s"), parse);
+                           snprintf(tmp, MSG_SIZ, _("your opponent kibitzes: %s"), parse);
                            SendToPlayer(tmp, strlen(tmp));
                        }
                        next_out = i+1; // [HGM] suppress printing in ICS window
@@ -3167,7 +3205,7 @@ read_from_ics(isr, closure, data, count, error)
                /* Header for a move list -- second line */
                /* Initial board will follow if this is a wild game */
                if (gameInfo.event != NULL) free(gameInfo.event);
-               sprintf(str, "ICS %s %s match", star_match[0], star_match[1]);
+               snprintf(str, MSG_SIZ, "ICS %s %s match", star_match[0], star_match[1]);
                gameInfo.event = StrSave(str);
                 /* [HGM] we switched variant. Translate boards if needed. */
                 VariantSwitch(boards[currentMove], StringToVariant(gameInfo.event));
@@ -3292,7 +3330,7 @@ read_from_ics(isr, closure, data, count, error)
                        flipView = appData.flipView;
                        DrawPosition(TRUE, boards[currentMove]);
                        DisplayBothClocks();
-                       sprintf(str, "%s vs. %s",
+                       snprintf(str, MSG_SIZ, "%s vs. %s",
                                gameInfo.white, gameInfo.black);
                        DisplayTitle(str);
                        gameMode = IcsIdle;
@@ -3362,7 +3400,7 @@ read_from_ics(isr, closure, data, count, error)
                } else {
                    player = star_match[2];
                }
-               sprintf(str, "%sobserve %s\n",
+               snprintf(str, MSG_SIZ, "%sobserve %s\n",
                        ics_prefix, StripHighlightAndTitle(player));
                SendToICS(str);
 
@@ -3624,14 +3662,14 @@ read_from_ics(isr, closure, data, count, error)
                      if (currentMove == 0 &&
                          gameMode == IcsPlayingWhite &&
                          appData.premoveWhite) {
-                       sprintf(str, "%s\n", appData.premoveWhiteText);
+                       snprintf(str, MSG_SIZ, "%s\n", appData.premoveWhiteText);
                        if (appData.debugMode)
                          fprintf(debugFP, "Sending premove:\n");
                        SendToICS(str);
                      } else if (currentMove == 1 &&
                                 gameMode == IcsPlayingBlack &&
                                 appData.premoveBlack) {
-                       sprintf(str, "%s\n", appData.premoveBlackText);
+                       snprintf(str, MSG_SIZ, "%s\n", appData.premoveBlackText);
                        if (appData.debugMode)
                          fprintf(debugFP, "Sending premove:\n");
                        SendToICS(str);
@@ -3682,7 +3720,7 @@ read_from_ics(isr, closure, data, count, error)
                             will tell us whether this is really bug or zh */
                          if (ics_getting_history == H_FALSE) {
                            ics_getting_history = H_REQUESTED;
-                           sprintf(str, "%smoves %d\n", ics_prefix, gamenum);
+                           snprintf(str, MSG_SIZ, "%smoves %d\n", ics_prefix, gamenum);
                            SendToICS(str);
                          }
                        }
@@ -3706,10 +3744,10 @@ read_from_ics(isr, closure, data, count, error)
                            char wh[16], bh[16];
                            PackHolding(wh, white_holding);
                            PackHolding(bh, black_holding);
-                           sprintf(str, "[%s-%s] %s-%s", wh, bh,
+                           snprintf(str, MSG_SIZ,"[%s-%s] %s-%s", wh, bh,
                                    gameInfo.white, gameInfo.black);
                        } else {
-                           sprintf(str, "%s [%s] vs. %s [%s]",
+                         snprintf(str, MSG_SIZ, "%s [%s] vs. %s [%s]",
                                    gameInfo.white, white_holding,
                                    gameInfo.black, black_holding);
                        }
@@ -3903,7 +3941,7 @@ ParseBoard12(string)
       if(twoBoards) { partnerUp = 1; flipView = !flipView; } // [HGM] dual
       if(partnerUp) DrawPosition(FALSE, partnerBoard);
       if(twoBoards) { partnerUp = 0; flipView = !flipView; } // [HGM] dual
-      sprintf(partnerStatus, "W: %d:%02d B: %d:%02d (%d-%d) %c", white_time/60000, (white_time%60000)/1000,
+      snprintf(partnerStatus, MSG_SIZ,"W: %d:%02d B: %d:%02d (%d-%d) %c", white_time/60000, (white_time%60000)/1000,
                 (black_time/60000), (black_time%60000)/1000, white_stren, black_stren, to_play);
       DisplayMessage(partnerStatus, "");
        partnerBoardValid = TRUE;
@@ -3959,7 +3997,7 @@ ParseBoard12(string)
             will tell us whether this is really bug or zh */
          if (ics_getting_history == H_FALSE) {
            ics_getting_history = H_REQUESTED; reqFlag = TRUE;
-           sprintf(str, "%smoves %d\n", ics_prefix, gamenum);
+           snprintf(str, MSG_SIZ, "%smoves %d\n", ics_prefix, gamenum);
            SendToICS(str);
          }
     }
@@ -3982,7 +4020,7 @@ ParseBoard12(string)
                   appData.getMoveList && !reqFlag) {
            /* Need to get game history */
            ics_getting_history = H_REQUESTED;
-           sprintf(str, "%smoves %d\n", ics_prefix, gamenum);
+           snprintf(str, MSG_SIZ, "%smoves %d\n", ics_prefix, gamenum);
            SendToICS(str);
        }
 
@@ -4000,7 +4038,7 @@ ParseBoard12(string)
        if (gamenum == gs_gamenum) {
            int klen = strlen(gs_kind);
            if (gs_kind[klen - 1] == '.') gs_kind[klen - 1] = NULLCHAR;
-           sprintf(str, "ICS %s", gs_kind);
+           snprintf(str, MSG_SIZ, "ICS %s", gs_kind);
            gameInfo.event = StrSave(str);
        } else {
            gameInfo.event = StrSave("ICS game");
@@ -4174,7 +4212,7 @@ ParseBoard12(string)
             type when starting to examine a game.  But if we ask for
             the move list, the move list header will tell us */
            ics_getting_history = H_REQUESTED;
-           sprintf(str, "%smoves %d\n", ics_prefix, gamenum);
+           snprintf(str, MSG_SIZ, "%smoves %d\n", ics_prefix, gamenum);
            SendToICS(str);
        }
     } else if (moveNum == forwardMostMove + 1 || moveNum == forwardMostMove
@@ -4213,7 +4251,7 @@ ParseBoard12(string)
            }
 #endif
            ics_getting_history = H_REQUESTED;
-           sprintf(str, "%smoves %d\n", ics_prefix, gamenum);
+           snprintf(str, MSG_SIZ, "%smoves %d\n", ics_prefix, gamenum);
            SendToICS(str);
        }
        forwardMostMove = backwardMostMove = currentMove = moveNum;
@@ -4275,7 +4313,7 @@ ParseBoard12(string)
 
          // str looks something like "Q/a1-a2"; kill the slash
          if(str[1] == '/')
-               sprintf(buf, "%c%s", str[0], str+2);
+           snprintf(buf, MSG_SIZ,"%c%s", str[0], str+2);
          else  safeStrCpy(buf, str, sizeof(buf)/sizeof(buf[0])); // might be castling
          if((prom = strstr(move_str, "=")) && !strstr(buf, "="))
                strcat(buf, prom); // long move lacks promo specification!
@@ -4339,7 +4377,7 @@ ParseBoard12(string)
            if ((gameMode == IcsPlayingWhite && WhiteOnMove(moveNum)) ||
                (gameMode == IcsPlayingBlack && !WhiteOnMove(moveNum))) {
                if (moveList[moveNum - 1][0] == NULLCHAR) {
-                   sprintf(str, _("Couldn't parse move \"%s\" from ICS"),
+                 snprintf(str, MSG_SIZ, _("Couldn't parse move \"%s\" from ICS"),
                            move_str);
                    DisplayError(str, 0);
                } else {
@@ -4361,7 +4399,7 @@ ParseBoard12(string)
                }
            } else if (gameMode == IcsObserving || gameMode == IcsExamining) {
              if (moveList[moveNum - 1][0] == NULLCHAR) {
-               sprintf(str, _("Couldn't parse move \"%s\" from ICS"), move_str);
+               snprintf(str, MSG_SIZ, _("Couldn't parse move \"%s\" from ICS"), move_str);
                DisplayError(str, 0);
              } else {
                if(gameInfo.variant == currentlyInitializedVariant) // [HGM] refrain sending moves engine can't understand!
@@ -4405,20 +4443,20 @@ ParseBoard12(string)
        gameInfo.variant != VariantCrazyhouse && !appData.noGUI) {
        if (tinyLayout || smallLayout) {
            if(gameInfo.variant == VariantNormal)
-               sprintf(str, "%s(%d) %s(%d) {%d %d}",
+             snprintf(str, MSG_SIZ, "%s(%d) %s(%d) {%d %d}",
                    gameInfo.white, white_stren, gameInfo.black, black_stren,
                    basetime, increment);
            else
-               sprintf(str, "%s(%d) %s(%d) {%d %d w%d}",
+             snprintf(str, MSG_SIZ, "%s(%d) %s(%d) {%d %d w%d}",
                    gameInfo.white, white_stren, gameInfo.black, black_stren,
                    basetime, increment, (int) gameInfo.variant);
        } else {
            if(gameInfo.variant == VariantNormal)
-               sprintf(str, "%s (%d) vs. %s (%d) {%d %d}",
+             snprintf(str, MSG_SIZ, "%s (%d) vs. %s (%d) {%d %d}",
                    gameInfo.white, white_stren, gameInfo.black, black_stren,
                    basetime, increment);
            else
-               sprintf(str, "%s (%d) vs. %s (%d) {%d %d %s}",
+             snprintf(str, MSG_SIZ, "%s (%d) vs. %s (%d) {%d %d %s}",
                    gameInfo.white, white_stren, gameInfo.black, black_stren,
                    basetime, increment, VariantName(gameInfo.variant));
        }
@@ -4472,7 +4510,7 @@ GetMoveListEvent()
     char buf[MSG_SIZ];
     if (appData.icsActive && gameMode != IcsIdle && ics_gamenum > 0) {
        ics_getting_history = H_REQUESTED;
-       sprintf(buf, "%smoves %d\n", ics_prefix, ics_gamenum);
+       snprintf(buf, MSG_SIZ, "%smoves %d\n", ics_prefix, ics_gamenum);
        SendToICS(buf);
     }
 }
@@ -4519,7 +4557,7 @@ SendMoveToProgram(moveNum, cps)
        buf[len++] = '\n';
        buf[len] = NULLCHAR;
       } else {
-       sprintf(buf, "%s\n", parseList[moveNum]);
+       snprintf(buf, MSG_SIZ,"%s\n", parseList[moveNum]);
       }
       SendToProgram(buf, cps);
     } else {
@@ -4576,7 +4614,7 @@ SendMoveToICS(moveType, fromX, fromY, toX, toY, promoChar)
 
     switch (moveType) {
       default:
-       sprintf(user_move, _("say Internal error; bad moveType %d (%d,%d-%d,%d)"),
+       snprintf(user_move, MSG_SIZ, _("say Internal error; bad moveType %d (%d,%d-%d,%d)"),
                (int)moveType, fromX, fromY, toX, toY);
        DisplayError(user_move + strlen("say "), 0);
        break;
@@ -4588,7 +4626,7 @@ SendMoveToICS(moveType, fromX, fromY, toX, toY, promoChar)
       case WhiteHSideCastleFR:
       case BlackHSideCastleFR:
       /* POP Fabien */
-       sprintf(user_move, "o-o\n");
+       snprintf(user_move, MSG_SIZ, "o-o\n");
        break;
       case WhiteQueenSideCastle:
       case BlackQueenSideCastle:
@@ -4598,7 +4636,7 @@ SendMoveToICS(moveType, fromX, fromY, toX, toY, promoChar)
       case WhiteASideCastleFR:
       case BlackASideCastleFR:
       /* POP Fabien */
-       sprintf(user_move, "o-o-o\n");
+       snprintf(user_move, MSG_SIZ, "o-o-o\n");
        break;
       case WhiteNonPromotion:
       case BlackNonPromotion:
@@ -4607,21 +4645,21 @@ SendMoveToICS(moveType, fromX, fromY, toX, toY, promoChar)
       case WhitePromotion:
       case BlackPromotion:
         if(gameInfo.variant == VariantShatranj || gameInfo.variant == VariantCourier || gameInfo.variant == VariantMakruk)
-            sprintf(user_move, "%c%c%c%c=%c\n",
+         snprintf(user_move, MSG_SIZ, "%c%c%c%c=%c\n",
                 AAA + fromX, ONE + fromY, AAA + toX, ONE + toY,
                PieceToChar(WhiteFerz));
         else if(gameInfo.variant == VariantGreat)
-            sprintf(user_move, "%c%c%c%c=%c\n",
+         snprintf(user_move, MSG_SIZ,"%c%c%c%c=%c\n",
                 AAA + fromX, ONE + fromY, AAA + toX, ONE + toY,
                PieceToChar(WhiteMan));
         else
-            sprintf(user_move, "%c%c%c%c=%c\n",
+         snprintf(user_move, MSG_SIZ, "%c%c%c%c=%c\n",
                 AAA + fromX, ONE + fromY, AAA + toX, ONE + toY,
                promoChar);
        break;
       case WhiteDrop:
       case BlackDrop:
-       sprintf(user_move, "%c@%c%c\n",
+       snprintf(user_move, MSG_SIZ, "%c@%c%c\n",
                ToUpper(PieceToChar((ChessSquare) fromX)),
                 AAA + toX, ONE + toY);
        break;
@@ -4629,7 +4667,7 @@ SendMoveToICS(moveType, fromX, fromY, toX, toY, promoChar)
       case WhiteCapturesEnPassant:
       case BlackCapturesEnPassant:
       case IllegalMove:  /* could be a variant we don't quite understand */
-       sprintf(user_move, "%c%c%c%c\n",
+       snprintf(user_move, MSG_SIZ,"%c%c%c%c\n",
                 AAA + fromX, ONE + fromY, AAA + toX, ONE + toY);
        break;
     }
@@ -4651,43 +4689,43 @@ UploadGameEvent()
        char buf[MSG_SIZ], *p, *fen, command[MSG_SIZ], bsetup = 0;
 
        if(ics_type == ICS_ICC) { // on ICC match ourselves in applicable variant
-           sprintf(command, "match %s", ics_handle);
+         snprintf(command,MSG_SIZ, "match %s", ics_handle);
        } else { // on FICS we must first go to general examine mode
          safeStrCpy(command, "examine\nbsetup", sizeof(command)/sizeof(command[0])); // and specify variant within it with bsetups
        }
        if(gameInfo.variant != VariantNormal) {
            // try figure out wild number, as xboard names are not always valid on ICS
            for(i=1; i<=36; i++) {
-               sprintf(buf, "wild/%d", i);
+             snprintf(buf, MSG_SIZ, "wild/%d", i);
                if(StringToVariant(buf) == gameInfo.variant) break;
            }
-           if(i<=36 && ics_type == ICS_ICC) sprintf(buf, "%s w%d\n", command, i);
-           else if(i == 22) sprintf(buf, "%s fr\n", command);
-           else sprintf(buf, "%s %s\n", command, VariantName(gameInfo.variant));
-       } else sprintf(buf, "%s\n", ics_type == ICS_ICC ? command : "examine\n"); // match yourself or examine
+           if(i<=36 && ics_type == ICS_ICC) snprintf(buf, MSG_SIZ,"%s w%d\n", command, i);
+           else if(i == 22) snprintf(buf,MSG_SIZ, "%s fr\n", command);
+           else snprintf(buf, MSG_SIZ,"%s %s\n", command, VariantName(gameInfo.variant));
+       } else snprintf(buf, MSG_SIZ,"%s\n", ics_type == ICS_ICC ? command : "examine\n"); // match yourself or examine
        SendToICS(ics_prefix);
        SendToICS(buf);
        if(startedFromSetupPosition || backwardMostMove != 0) {
          fen = PositionToFEN(backwardMostMove, NULL);
          if(ics_type == ICS_ICC) { // on ICC we can simply send a complete FEN to set everything
-           sprintf(buf, "loadfen %s\n", fen);
+           snprintf(buf, MSG_SIZ,"loadfen %s\n", fen);
            SendToICS(buf);
          } else { // FICS: everything has to set by separate bsetup commands
            p = strchr(fen, ' '); p[0] = NULLCHAR; // cut after board
-           sprintf(buf, "bsetup fen %s\n", fen);
+           snprintf(buf, MSG_SIZ,"bsetup fen %s\n", fen);
            SendToICS(buf);
            if(!WhiteOnMove(backwardMostMove)) {
                SendToICS("bsetup tomove black\n");
            }
            i = (strchr(p+3, 'K') != NULL) + 2*(strchr(p+3, 'Q') != NULL);
-           sprintf(buf, "bsetup wcastle %s\n", castlingStrings[i]);
+           snprintf(buf, MSG_SIZ,"bsetup wcastle %s\n", castlingStrings[i]);
            SendToICS(buf);
            i = (strchr(p+3, 'k') != NULL) + 2*(strchr(p+3, 'q') != NULL);
-           sprintf(buf, "bsetup bcastle %s\n", castlingStrings[i]);
+           snprintf(buf, MSG_SIZ, "bsetup bcastle %s\n", castlingStrings[i]);
            SendToICS(buf);
            i = boards[backwardMostMove][EP_STATUS];
            if(i >= 0) { // set e.p.
-               sprintf(buf, "bsetup eppos %c\n", i+AAA);
+             snprintf(buf, MSG_SIZ,"bsetup eppos %c\n", i+AAA);
                SendToICS(buf);
            }
            bsetup++;
@@ -4698,7 +4736,7 @@ UploadGameEvent()
     }
     for(i = backwardMostMove; i<last; i++) {
        char buf[20];
-       sprintf(buf, "%s\n", parseList[i]);
+       snprintf(buf, sizeof(buf)/sizeof(buf[0]),"%s\n", parseList[i]);
        SendToICS(buf);
     }
     SendToICS(ics_prefix);
@@ -4712,11 +4750,11 @@ CoordsToComputerAlgebraic(rf, ff, rt, ft, promoChar, move)
      char move[7];
 {
     if (rf == DROP_RANK) {
-       sprintf(move, "%c@%c%c\n",
+      sprintf(move, "%c@%c%c\n",
                 ToUpper(PieceToChar((ChessSquare) ff)), AAA + ft, ONE + rt);
     } else {
        if (promoChar == 'x' || promoChar == NULLCHAR) {
-           sprintf(move, "%c%c%c%c\n",
+         sprintf(move, "%c%c%c%c\n",
                     AAA + ff, ONE + rf, AAA + ft, ONE + rt);
        } else {
            sprintf(move, "%c%c%c%c%c\n",
@@ -5504,7 +5542,7 @@ SendBoard(cps, moveNum)
 
     if (cps->useSetboard) {
       char* fen = PositionToFEN(moveNum, cps->fenOverride);
-      sprintf(message, "setboard %s\n", fen);
+      snprintf(message, MSG_SIZ,"setboard %s\n", fen);
       SendToProgram(message, cps);
       free(fen);
 
@@ -5522,10 +5560,10 @@ SendBoard(cps, moveNum)
        bp = &boards[moveNum][i][BOARD_LEFT];
         for (j = BOARD_LEFT; j < BOARD_RGHT; j++, bp++) {
          if ((int) *bp < (int) BlackPawn) {
-           sprintf(message, "%c%c%c\n", PieceToChar(*bp),
+           snprintf(message, MSG_SIZ, "%c%c%c\n", PieceToChar(*bp),
                     AAA + j, ONE + i);
             if(message[0] == '+' || message[0] == '~') {
-                sprintf(message, "%c%c%c+\n",
+             snprintf(message, MSG_SIZ,"%c%c%c+\n",
                         PieceToChar((ChessSquare)(DEMOTED *bp)),
                         AAA + j, ONE + i);
             }
@@ -5544,10 +5582,10 @@ SendBoard(cps, moveNum)
         for (j = BOARD_LEFT; j < BOARD_RGHT; j++, bp++) {
          if (((int) *bp != (int) EmptySquare)
              && ((int) *bp >= (int) BlackPawn)) {
-           sprintf(message, "%c%c%c\n", ToUpper(PieceToChar(*bp)),
+           snprintf(message,MSG_SIZ, "%c%c%c\n", ToUpper(PieceToChar(*bp)),
                     AAA + j, ONE + i);
             if(message[0] == '+' || message[0] == '~') {
-                sprintf(message, "%c%c%c+\n",
+             snprintf(message, MSG_SIZ,"%c%c%c+\n",
                         PieceToChar((ChessSquare)(DEMOTED *bp)),
                         AAA + j, ONE + i);
             }
@@ -6102,10 +6140,10 @@ FinishMove(moveType, fromX, fromY, toX, toY, promoChar)
       gameMode = MachinePlaysBlack;
       StartClocks();
       SetGameInfo();
-      sprintf(buf, "%s vs. %s", gameInfo.white, gameInfo.black);
+      snprintf(buf, MSG_SIZ, "%s vs. %s", gameInfo.white, gameInfo.black);
       DisplayTitle(buf);
       if (first.sendName) {
-       sprintf(buf, "name %s\n", gameInfo.white);
+       snprintf(buf, MSG_SIZ,"name %s\n", gameInfo.white);
        SendToProgram(buf, &first);
       }
       StartClocks();
@@ -6990,7 +7028,7 @@ char *SendMoveToBookUser(int moveNr, ChessProgramState *cps, int initial)
        // after a book hit we never send 'go', and the code after the call to this routine
        // has '&& !bookHit' added to suppress potential sending there (based on 'firstMove').
        char buf[MSG_SIZ];
-       sprintf(buf, "%s%s\n", (cps->useUsermove ? "usermove " : ""), bookHit); // force book move into program supposed to play it
+       snprintf(buf, MSG_SIZ, "%s%s\n", (cps->useUsermove ? "usermove " : ""), bookHit); // force book move into program supposed to play it
        SendToProgram(buf, cps);
        if(!initial) firstMove = FALSE; // normally we would clear the firstMove condition after return & sending 'go'
     } else if(initial) { // 'go' was needed irrespective of firstMove, and it has to be done in this routine
@@ -7142,10 +7180,10 @@ FakeBookMove: // [HGM] book: we jump here to simulate machine moves after book h
         if (!ParseOneMove(machineMove, forwardMostMove, &moveType,
                               &fromX, &fromY, &toX, &toY, &promoChar)) {
            /* Machine move could not be parsed; ignore it. */
-            sprintf(buf1, _("Illegal move \"%s\" from %s machine"),
+         snprintf(buf1, MSG_SIZ*10, _("Illegal move \"%s\" from %s machine"),
                    machineMove, cps->which);
            DisplayError(buf1, 0);
-            sprintf(buf1, "Xboard: Forfeit due to invalid move: %s (%c%c%c%c) res=%d",
+            snprintf(buf1, MSG_SIZ*10, "Xboard: Forfeit due to invalid move: %s (%c%c%c%c) res=%d",
                     machineMove, fromX+AAA, fromY+ONE, toX+AAA, toY+ONE, moveType);
            if (gameMode == TwoMachinesPlay) {
              GameEnds(machineWhite ? BlackWins : WhiteWins,
@@ -7170,7 +7208,7 @@ FakeBookMove: // [HGM] book: we jump here to simulate machine moves after book h
                 fprintf(debugFP, "castling rights\n");
            }
             if(moveType == IllegalMove) {
-                sprintf(buf1, "Xboard: Forfeit due to illegal move: %s (%c%c%c%c)%c",
+             snprintf(buf1, MSG_SIZ*10, "Xboard: Forfeit due to illegal move: %s (%c%c%c%c)%c",
                         machineMove, fromX+AAA, fromY+ONE, toX+AAA, toY+ONE, 0);
                 GameEnds(machineWhite ? BlackWins : WhiteWins,
                            buf1, GE_XBOARD);
@@ -7256,7 +7294,7 @@ FakeBookMove: // [HGM] book: we jump here to simulate machine moves after book h
          if(appData.autoKibitz && !appData.icsEngineAnalyze ) { /* [HGM] kibitz: send most-recent PV info to ICS */
                char buf[3*MSG_SIZ];
 
-               sprintf(buf, "kibitz !!! %+.2f/%d (%.2f sec, %u nodes, %.0f knps) PV=%s\n",
+               snprintf(buf, 3*MSG_SIZ, "kibitz !!! %+.2f/%d (%.2f sec, %u nodes, %.0f knps) PV=%s\n",
                        programStats.score / 100.,
                        programStats.depth,
                        programStats.time / 100.,
@@ -7497,7 +7535,7 @@ if(appData.debugMode) fprintf(debugFP, "nodes = %d, %lld\n", (int) programStats.
            cps->analysisSupport = FALSE;
            cps->analyzing = FALSE;
            Reset(FALSE, TRUE);
-           sprintf(buf2, _("%s does not support analysis"), cps->tidy);
+           snprintf(buf2,MSG_SIZ, _("%s does not support analysis"), cps->tidy);
            DisplayError(buf2, 0);
            return;
        }
@@ -7556,7 +7594,7 @@ if(appData.debugMode) fprintf(debugFP, "nodes = %d, %lld\n", (int) programStats.
        DisplayMove(currentMove-1); /* before DisplayMoveError */
        SwitchClocks(forwardMostMove-1); // [HGM] race
        DisplayBothClocks();
-       sprintf(buf1, _("Illegal move \"%s\" (rejected by %s chess program)"),
+       snprintf(buf1, 10*MSG_SIZ, _("Illegal move \"%s\" (rejected by %s chess program)"),
                parseList[currentMove], cps->which);
        DisplayMoveError(buf1);
        DrawPosition(FALSE, boards[currentMove]);
@@ -7911,13 +7949,13 @@ if(appData.debugMode) fprintf(debugFP, "nodes = %d, %lld\n", (int) programStats.
                     [AS] Protect the thinkOutput buffer from overflow... this
                     is only useful if buf1 hasn't overflowed first!
                 */
-               sprintf(thinkOutput, "[%d]%c%+.2f %s%s",
-                       plylev,
-                       (gameMode == TwoMachinesPlay ?
-                        ToUpper(cps->twoMachinesColor[0]) : ' '),
-                       ((double) curscore) / 100.0,
-                       prefixHint ? lastHint : "",
-                       prefixHint ? " " : "" );
+               snprintf(thinkOutput, sizeof(thinkOutput)/sizeof(thinkOutput[0]), "[%d]%c%+.2f %s%s",
+                        plylev,
+                        (gameMode == TwoMachinesPlay ?
+                         ToUpper(cps->twoMachinesColor[0]) : ' '),
+                        ((double) curscore) / 100.0,
+                        prefixHint ? lastHint : "",
+                        prefixHint ? " " : "" );
 
                 if( buf1[0] != NULLCHAR ) {
                     unsigned max_len = sizeof(thinkOutput) - strlen(thinkOutput) - 1;
@@ -7943,7 +7981,7 @@ if(appData.debugMode) fprintf(debugFP, "nodes = %d, %lld\n", (int) programStats.
                 * if there is only 1 legal move
                  */
                sscanf(p, "(only move) %s", buf1);
-               sprintf(thinkOutput, "%s (only move)", buf1);
+               snprintf(thinkOutput, sizeof(thinkOutput)/sizeof(thinkOutput[0]), "%s (only move)", buf1);
                sprintf(programStats.movelist, "%s (only move)", buf1);
                programStats.depth = 1;
                programStats.nr_moves = 1;
@@ -8152,7 +8190,7 @@ ParseGameHistory(game)
            break;
          case AmbiguousMove:
            /* bug? */
-           sprintf(buf, _("Ambiguous move in ICS output: \"%s\""), yy_text);
+           snprintf(buf, MSG_SIZ, _("Ambiguous move in ICS output: \"%s\""), yy_text);
   if (appData.debugMode) {
     fprintf(debugFP, "Ambiguous move from ICS: '%s'\n", yy_text);
     fprintf(debugFP, "board L=%d, R=%d, H=%d, holdings=%d\n", BOARD_LEFT, BOARD_RGHT, BOARD_HEIGHT, gameInfo.holdingsWidth);
@@ -8162,7 +8200,7 @@ ParseGameHistory(game)
            return;
          case ImpossibleMove:
            /* bug? */
-           sprintf(buf, _("Illegal move in ICS output: \"%s\""), yy_text);
+           snprintf(buf, MSG_SIZ, _("Illegal move in ICS output: \"%s\""), yy_text);
   if (appData.debugMode) {
     fprintf(debugFP, "Impossible move from ICS: '%s'\n", yy_text);
     fprintf(debugFP, "board L=%d, R=%d, H=%d, holdings=%d\n", BOARD_LEFT, BOARD_RGHT, BOARD_HEIGHT, gameInfo.holdingsWidth);
@@ -8695,7 +8733,7 @@ void SendEgtPath(ChessProgramState *cps)
            if( appData.defaultPathEGTB && appData.defaultPathEGTB[0] &&
                strcmp(name, ",nalimov:") == 0 ) {
                // take nalimov path from the menu-changeable option first, if it is defined
-               sprintf(buf, "egtpath nalimov %s\n", appData.defaultPathEGTB);
+             snprintf(buf, MSG_SIZ, "egtpath nalimov %s\n", appData.defaultPathEGTB);
                SendToProgram(buf,cps);     // send egtbpath command for nalimov
            } else
            if( (s = StrStr(appData.egtFormats, name+1)) == appData.egtFormats ||
@@ -8705,7 +8743,7 @@ void SendEgtPath(ChessProgramState *cps)
                while(*r && *r != ',') r++; // path info is everything upto next ';' or end of string
                c = *r; *r = 0;             // temporarily null-terminate path info
                    *--q = 0;               // strip of trailig ':' from name
-                   sprintf(buf, "egtpath %s %s\n", name+1, s);
+                   snprintf(buf, MSG_SIZ, "egtpath %s %s\n", name+1, s);
                *r = c;
                SendToProgram(buf,cps);     // send egtbpath command for this format
            }
@@ -8726,12 +8764,12 @@ InitChessProgram(cps, setup)
     /* [HGM] some new WB protocol commands to configure engine are sent now, if engine supports them */
     /*       moved to before sending initstring in 4.3.15, so Polyglot can delay UCI 'isready' to recepton of 'new' */
     if(cps->memSize) { /* [HGM] memory */
-       sprintf(buf, "memory %d\n", appData.defaultHashSize + appData.defaultCacheSizeEGTB);
+      snprintf(buf, MSG_SIZ, "memory %d\n", appData.defaultHashSize + appData.defaultCacheSizeEGTB);
        SendToProgram(buf, cps);
     }
     SendEgtPath(cps); /* [HGM] EGT */
     if(cps->maxCores) { /* [HGM] SMP: (protocol specified must be last settings command before new!) */
-       sprintf(buf, "cores %d\n", appData.smpCores);
+      snprintf(buf, MSG_SIZ, "cores %d\n", appData.smpCores);
        SendToProgram(buf, cps);
     }
 
@@ -8744,7 +8782,7 @@ InitChessProgram(cps, setup)
       char *v = VariantName(gameInfo.variant);
       if (cps->protocolVersion != 1 && StrStr(cps->variants, v) == NULL) {
         /* [HGM] in protocol 1 we have to assume all variants valid */
-       sprintf(buf, _("Variant %s not supported by %s"), v, cps->tidy);
+       snprintf(buf, MSG_SIZ, _("Variant %s not supported by %s"), v, cps->tidy);
        DisplayFatalError(buf, 0, 1);
        return;
       }
@@ -8768,14 +8806,14 @@ InitChessProgram(cps, setup)
            overruled = gameInfo.boardWidth != 10 || gameInfo.boardHeight != 8 || gameInfo.holdingsSize != 8;
 
       if(overruled) {
-           sprintf(b, "%dx%d+%d_%s", gameInfo.boardWidth, gameInfo.boardHeight,
-                               gameInfo.holdingsSize, VariantName(gameInfo.variant)); // cook up sized variant name
+       snprintf(b, MSG_SIZ, "%dx%d+%d_%s", gameInfo.boardWidth, gameInfo.boardHeight,
+                gameInfo.holdingsSize, VariantName(gameInfo.variant)); // cook up sized variant name
            /* [HGM] varsize: try first if this defiant size variant is specifically known */
            if(StrStr(cps->variants, b) == NULL) {
                // specific sized variant not known, check if general sizing allowed
                if (cps->protocolVersion != 1) { // for protocol 1 we cannot check and hope for the best
                    if(StrStr(cps->variants, "boardsize") == NULL) {
-                       sprintf(buf, "Board size %dx%d+%d not supported by %s",
+                    snprintf(buf, MSG_SIZ, "Board size %dx%d+%d not supported by %s",
                             gameInfo.boardWidth, gameInfo.boardHeight, gameInfo.holdingsSize, cps->tidy);
                        DisplayFatalError(buf, 0, 1);
                        return;
@@ -8783,8 +8821,8 @@ InitChessProgram(cps, setup)
                    /* [HGM] here we really should compare with the maximum supported board size */
                }
            }
-      } else sprintf(b, "%s", VariantName(gameInfo.variant));
-      sprintf(buf, "variant %s\n", b);
+      } else snprintf(b, MSG_SIZ,"%s", VariantName(gameInfo.variant));
+      snprintf(buf, MSG_SIZ, "variant %s\n", b);
       SendToProgram(buf, cps);
     }
     currentlyInitializedVariant = gameInfo.variant;
@@ -8823,7 +8861,7 @@ InitChessProgram(cps, setup)
        SendToProgram("easy\n", cps);
     }
     if (cps->usePing) {
-      sprintf(buf, "ping %d\n", ++cps->lastPing);
+      snprintf(buf, MSG_SIZ, "ping %d\n", ++cps->lastPing);
       SendToProgram(buf, cps);
     }
     cps->initDone = TRUE;
@@ -8856,7 +8894,7 @@ StartChessProgram(cps)
     }
 
     if (err != 0) {
-       sprintf(buf, _("Startup failure on '%s'"), cps->program);
+      snprintf(buf, MSG_SIZ, _("Startup failure on '%s'"), cps->program);
        DisplayFatalError(buf, err, 1);
        cps->pr = NoProc;
        cps->isr = NULL;
@@ -8865,7 +8903,7 @@ StartChessProgram(cps)
 
     cps->isr = AddInputSource(cps->pr, TRUE, ReceiveFromProgram, cps);
     if (cps->protocolVersion > 1) {
-      sprintf(buf, "xboard\nprotover %d\n", cps->protocolVersion);
+      snprintf(buf, MSG_SIZ, "xboard\nprotover %d\n", cps->protocolVersion);
       cps->nrOptions = 0; // [HGM] options: clear all engine-specific options
       cps->comboCnt = 0;  //                and values of combo boxes
       SendToProgram(buf, cps);
@@ -9057,7 +9095,7 @@ GameEnds(result, resultDetails, whosays)
                                result, (signed char)boards[forwardMostMove][EP_STATUS], forwardMostMove);
                      }
                      if(result != trueResult) {
-                             sprintf(buf, "False win claim: '%s'", resultDetails);
+                       snprintf(buf, MSG_SIZ, "False win claim: '%s'", resultDetails);
                              result = claimer == 'w' ? BlackWins : WhiteWins;
                              resultDetails = buf;
                      }
@@ -9068,7 +9106,7 @@ GameEnds(result, resultDetails, whosays)
                         (claimer=='b')==(forwardMostMove&1))
                                                                                   ) {
                       /* [HGM] verify: draws that were not flagged are false claims */
-                      sprintf(buf, "False draw claim: '%s'", resultDetails);
+                 snprintf(buf, MSG_SIZ, "False draw claim: '%s'", resultDetails);
                       result = claimer == 'w' ? BlackWins : WhiteWins;
                       resultDetails = buf;
                 }
@@ -9090,7 +9128,7 @@ GameEnds(result, resultDetails, whosays)
                }
                if(k <= 1) {
                        result = GameIsDrawn;
-                       sprintf(buf, "%s but bare king", resultDetails);
+                       snprintf(buf, MSG_SIZ, "%s but bare king", resultDetails);
                        resultDetails = buf;
                }
            }
@@ -9140,7 +9178,7 @@ GameEnds(result, resultDetails, whosays)
                gameMode == IcsPlayingBlack ||
                gameMode == BeginningOfGame) {
                char buf[MSG_SIZ];
-               sprintf(buf, "result %s {%s}\n", PGNResult(result),
+               snprintf(buf, MSG_SIZ, "result %s {%s}\n", PGNResult(result),
                        resultDetails);
                if (first.pr != NoProc) {
                    SendToProgram(buf, &first);
@@ -9223,7 +9261,7 @@ GameEnds(result, resultDetails, whosays)
            SendToProgram("force\n", &first);
            if (first.usePing) {
              char buf[MSG_SIZ];
-             sprintf(buf, "ping %d\n", ++first.lastPing);
+             snprintf(buf, MSG_SIZ, "ping %d\n", ++first.lastPing);
              SendToProgram(buf, &first);
            }
        }
@@ -9249,7 +9287,7 @@ GameEnds(result, resultDetails, whosays)
            SendToProgram("force\n", &second);
            if (second.usePing) {
              char buf[MSG_SIZ];
-             sprintf(buf, "ping %d\n", ++second.lastPing);
+             snprintf(buf, MSG_SIZ, "ping %d\n", ++second.lastPing);
              SendToProgram(buf, &second);
            }
        }
@@ -9303,10 +9341,10 @@ GameEnds(result, resultDetails, whosays)
            return;
        } else {
            gameMode = nextGameMode;
-           sprintf(buf, _("Match %s vs. %s: final score %d-%d-%d"),
-                   first.tidy, second.tidy,
-                   first.matchWins, second.matchWins,
-                   appData.matchGames - (first.matchWins + second.matchWins));
+           snprintf(buf, MSG_SIZ, _("Match %s vs. %s: final score %d-%d-%d"),
+                    first.tidy, second.tidy,
+                    first.matchWins, second.matchWins,
+                    appData.matchGames - (first.matchWins + second.matchWins));
            popupRequested++; // [HGM] crash: postpone to after resetting endingGame
        }
     }
@@ -9337,11 +9375,12 @@ FeedMovesToProgram(cps, upto)
       fprintf(debugFP, "Feeding %smoves %d through %d to %s chess program\n",
              startedFromSetupPosition ? "position and " : "",
              backwardMostMove, upto, cps->which);
-    if(currentlyInitializedVariant != gameInfo.variant) { char buf[MSG_SIZ];
+    if(currentlyInitializedVariant != gameInfo.variant) {
+      char buf[MSG_SIZ];
         // [HGM] variantswitch: make engine aware of new variant
        if(cps->protocolVersion > 1 && StrStr(cps->variants, VariantName(gameInfo.variant)) == NULL)
                return; // [HGM] refrain from feeding moves altogether if variant is unsupported!
-       sprintf(buf, "variant %s\n", VariantName(gameInfo.variant));
+       snprintf(buf, MSG_SIZ, "variant %s\n", VariantName(gameInfo.variant));
        SendToProgram(buf, cps);
         currentlyInitializedVariant = gameInfo.variant;
     }
@@ -9709,7 +9748,7 @@ LoadGameOneMove(readAhead)
        if (appData.testLegality) {
            if (appData.debugMode)
              fprintf(debugFP, "Parsed IllegalMove: %s\n", yy_text);
-           sprintf(move, _("Illegal move: %d.%s%s"),
+           snprintf(move, MSG_SIZ, _("Illegal move: %d.%s%s"),
                    (forwardMostMove / 2) + 1,
                    WhiteOnMove(forwardMostMove) ? " " : ".. ", yy_text);
            DisplayError(move, 0);
@@ -9729,7 +9768,7 @@ LoadGameOneMove(readAhead)
       case AmbiguousMove:
        if (appData.debugMode)
          fprintf(debugFP, "Parsed AmbiguousMove: %s\n", yy_text);
-       sprintf(move, _("Ambiguous move: %d.%s%s"),
+       snprintf(move, MSG_SIZ, _("Ambiguous move: %d.%s%s"),
                (forwardMostMove / 2) + 1,
                WhiteOnMove(forwardMostMove) ? " " : ".. ", yy_text);
        DisplayError(move, 0);
@@ -9740,7 +9779,7 @@ LoadGameOneMove(readAhead)
       case ImpossibleMove:
        if (appData.debugMode)
          fprintf(debugFP, "Parsed ImpossibleMove (type = %d): %s\n", moveType, yy_text);
-       sprintf(move, _("Illegal move: %d.%s%s"),
+       snprintf(move, MSG_SIZ, _("Illegal move: %d.%s%s"),
                (forwardMostMove / 2) + 1,
                WhiteOnMove(forwardMostMove) ? " " : ".. ", yy_text);
        DisplayError(move, 0);
@@ -10019,7 +10058,7 @@ LoadGame(f, gameNumber, title, useList)
            DisplayTitle(buf);
     } else if (*title != NULLCHAR) {
        if (gameNumber > 1) {
-           sprintf(buf, "%s %d", title, gameNumber);
+         snprintf(buf, MSG_SIZ, "%s %d", title, gameNumber);
            DisplayTitle(buf);
        } else {
            DisplayTitle(title);
@@ -10560,7 +10599,7 @@ int i, j;
     }
 
     if (positionNumber > 1) {
-       sprintf(line, "%s %d", title, positionNumber);
+      snprintf(line, MSG_SIZ, "%s %d", title, positionNumber);
        DisplayTitle(line);
     } else {
        DisplayTitle(title);
@@ -10780,15 +10819,14 @@ SaveGamePGN(f)
        }
 
        /* Format move number */
-       if ((i % 2) == 0) {
-           sprintf(numtext, "%d.", (i - offset)/2 + 1);
-       } else {
-           if (newblock) {
-               sprintf(numtext, "%d...", (i - offset)/2 + 1);
-           } else {
-               numtext[0] = NULLCHAR;
-           }
-       }
+       if ((i % 2) == 0)
+         snprintf(numtext, sizeof(numtext)/sizeof(numtext[0]),"%d.", (i - offset)/2 + 1);
+        else
+         if (newblock)
+           snprintf(numtext, sizeof(numtext)/sizeof(numtext[0]), "%d...", (i - offset)/2 + 1);
+         else
+           numtext[0] = NULLCHAR;
+
        numlen = strlen(numtext);
        newblock = FALSE;
 
@@ -10831,18 +10869,25 @@ SaveGamePGN(f)
 
             seconds = (pvInfoList[i].time+5)/10; // deci-seconds, rounded to nearest
 
-            if( seconds <= 0) buf[0] = 0; else
-            if( seconds < 30 ) sprintf(buf, " %3.1f%c", seconds/10., 0); else {
-               seconds = (seconds + 4)/10; // round to full seconds
-               if( seconds < 60 ) sprintf(buf, " %d%c", seconds, 0); else
-                                  sprintf(buf, " %d:%02d%c", seconds/60, seconds%60, 0);
-           }
+            if( seconds <= 0)
+             buf[0] = 0;
+           else
+             if( seconds < 30 )
+               snprintf(buf, MSG_SIZ, " %3.1f%c", seconds/10., 0);
+             else
+               {
+                 seconds = (seconds + 4)/10; // round to full seconds
+                 if( seconds < 60 )
+                   snprintf(buf, MSG_SIZ, " %d%c", seconds, 0);
+                 else
+                   snprintf(buf, MSG_SIZ, " %d:%02d%c", seconds/60, seconds%60, 0);
+               }
 
-            sprintf( move_buffer, "{%s%.2f/%d%s}",
-                pvInfoList[i].score >= 0 ? "+" : "",
-                pvInfoList[i].score / 100.0,
-                pvInfoList[i].depth,
-               buf );
+            snprintf( move_buffer, sizeof(move_buffer)/sizeof(move_buffer[0]),"{%s%.2f/%d%s}",
+                     pvInfoList[i].score >= 0 ? "+" : "",
+                     pvInfoList[i].score / 100.0,
+                     pvInfoList[i].depth,
+                     buf );
 
            movelen = strlen(move_buffer); /* [HGM] pgn: line-break point after move */
 
@@ -11147,14 +11192,13 @@ RegisterMove()
          fprintf(debugFP, "Saving %s for game %d\n",
                  cmailMove[lastLoadGameNumber - 1], lastLoadGameNumber);
 
-       sprintf(string,
-               "%s.game.out.%d", appData.cmailGameName, lastLoadGameNumber);
+       snprintf(string, MSG_SIZ, "%s.game.out.%d", appData.cmailGameName, lastLoadGameNumber);
 
        f = fopen(string, "w");
        if (appData.oldSaveStyle) {
            SaveGameOldStyle(f); /* also closes the file */
 
-           sprintf(string, "%s.pos.out", appData.cmailGameName);
+           snprintf(string, MSG_SIZ, "%s.pos.out", appData.cmailGameName);
            f = fopen(string, "w");
            SavePosition(f, 0, NULL); /* also closes the file */
        } else {
@@ -11200,7 +11244,7 @@ MailMoveEvent()
 
 #if CMAIL_PROHIBIT_REMAIL
     if (cmailMailedMove) {
-       sprintf(msg, _("You have already mailed a move.\nWait until a move arrives from your opponent.\nTo resend the same move, type\n\"cmail -remail -game %s\"\non the command line."), appData.cmailGameName);
+      snprintf(msg, MSG_SIZ, _("You have already mailed a move.\nWait until a move arrives from your opponent.\nTo resend the same move, type\n\"cmail -remail -game %s\"\non the command line."), appData.cmailGameName);
        DisplayError(msg, 0);
        return;
     }
@@ -11210,8 +11254,8 @@ MailMoveEvent()
 
     if (   cmailMailedMove
        || (nCmailMovesRegistered + nCmailResults == nCmailGames)) {
-       sprintf(string, partCommandString,
-               appData.debugMode ? " -v" : "", appData.cmailGameName);
+      snprintf(string, MSG_SIZ, partCommandString,
+              appData.debugMode ? " -v" : "", appData.cmailGameName);
        commandOutput = popen(string, "r");
 
        if (commandOutput == NULL) {
@@ -11241,10 +11285,10 @@ MailMoveEvent()
                if (   archived
                    && (   (arcDir = (char *) getenv("CMAIL_ARCDIR"))
                        != NULL)) {
-                   sprintf(buffer, "%s/%s.%s.archive",
-                           arcDir,
-                           appData.cmailGameName,
-                           gameInfo.date);
+                 snprintf(buffer, MSG_SIZ, "%s/%s.%s.archive",
+                          arcDir,
+                          appData.cmailGameName,
+                          gameInfo.date);
                    LoadGameFromFile(buffer, 1, buffer, FALSE);
                    cmailMsgLoaded = FALSE;
                }
@@ -11277,17 +11321,17 @@ CmailMsg()
     if (!cmailMsgLoaded) return "";
 
     if (cmailMailedMove) {
-       sprintf(cmailMsg, _("Waiting for reply from opponent\n"));
+      snprintf(cmailMsg, MSG_SIZ, _("Waiting for reply from opponent\n"));
     } else {
        /* Create a list of games left */
-       sprintf(string, "[");
+      snprintf(string, MSG_SIZ, "[");
        for (i = 0; i < nCmailGames; i ++) {
            if (! (   cmailMoveRegistered[i]
                   || (cmailResult[i] == CMAIL_OLD_RESULT))) {
                if (prependComma) {
-                   sprintf(number, ",%d", i + 1);
+                   snprintf(number, sizeof(number)/sizeof(number[0]), ",%d", i + 1);
                } else {
-                   sprintf(number, "%d", i + 1);
+                   snprintf(number, sizeof(number)/sizeof(number[0]), "%d", i + 1);
                    prependComma = 1;
                }
 
@@ -11299,41 +11343,36 @@ CmailMsg()
        if (nCmailMovesRegistered + nCmailResults == 0) {
            switch (nCmailGames) {
              case 1:
-               sprintf(cmailMsg,
-                       _("Still need to make move for game\n"));
+               snprintf(cmailMsg, MSG_SIZ, _("Still need to make move for game\n"));
                break;
 
              case 2:
-               sprintf(cmailMsg,
-                       _("Still need to make moves for both games\n"));
+               snprintf(cmailMsg, MSG_SIZ, _("Still need to make moves for both games\n"));
                break;
 
              default:
-               sprintf(cmailMsg,
-                       _("Still need to make moves for all %d games\n"),
-                       nCmailGames);
+               snprintf(cmailMsg, MSG_SIZ, _("Still need to make moves for all %d games\n"),
+                        nCmailGames);
                break;
            }
        } else {
            switch (nCmailGames - nCmailMovesRegistered - nCmailResults) {
              case 1:
-               sprintf(cmailMsg,
-                       _("Still need to make a move for game %s\n"),
-                       string);
+               snprintf(cmailMsg, MSG_SIZ, _("Still need to make a move for game %s\n"),
+                        string);
                break;
 
              case 0:
                if (nCmailResults == nCmailGames) {
-                   sprintf(cmailMsg, _("No unfinished games\n"));
+                 snprintf(cmailMsg, MSG_SIZ, _("No unfinished games\n"));
                } else {
-                   sprintf(cmailMsg, _("Ready to send mail\n"));
+                 snprintf(cmailMsg, MSG_SIZ, _("Ready to send mail\n"));
                }
                break;
 
              default:
-               sprintf(cmailMsg,
-                       _("Still need to make moves for games %s\n"),
-                       string);
+               snprintf(cmailMsg, MSG_SIZ, _("Still need to make moves for games %s\n"),
+                        string);
            }
        }
     }
@@ -11488,9 +11527,9 @@ EditCommentEvent()
     if (currentMove < 1 || parseList[currentMove - 1][0] == NULLCHAR) {
       safeStrCpy(title, _("Edit comment"), sizeof(title)/sizeof(title[0]));
     } else {
-      sprintf(title, _("Edit comment on %d.%s%s"), (currentMove - 1) / 2 + 1,
-             WhiteOnMove(currentMove - 1) ? " " : ".. ",
-             parseList[currentMove - 1]);
+      snprintf(title, MSG_SIZ, _("Edit comment on %d.%s%s"), (currentMove - 1) / 2 + 1,
+              WhiteOnMove(currentMove - 1) ? " " : ".. ",
+              parseList[currentMove - 1]);
     }
 
     EditCommentPopUp(currentMove, title, commentList[currentMove]);
@@ -11600,10 +11639,10 @@ MachineWhiteEvent()
     pausing = FALSE;
     ModeHighlight();
     SetGameInfo();
-    sprintf(buf, "%s vs. %s", gameInfo.white, gameInfo.black);
+    snprintf(buf, MSG_SIZ, "%s vs. %s", gameInfo.white, gameInfo.black);
     DisplayTitle(buf);
     if (first.sendName) {
-      sprintf(buf, "name %s\n", gameInfo.black);
+      snprintf(buf, MSG_SIZ, "name %s\n", gameInfo.black);
       SendToProgram(buf, &first);
     }
     if (first.sendTime) {
@@ -11643,8 +11682,8 @@ MachineWhiteEvent()
 void
 MachineBlackEvent()
 {
-    char buf[MSG_SIZ];
-   char *bookHit = NULL;
+  char buf[MSG_SIZ];
+  char *bookHit = NULL;
 
     if (appData.noChessProgram || (gameMode == MachinePlaysBlack))
        return;
@@ -11677,10 +11716,10 @@ MachineBlackEvent()
     pausing = FALSE;
     ModeHighlight();
     SetGameInfo();
-    sprintf(buf, "%s vs. %s", gameInfo.white, gameInfo.black);
+    snprintf(buf, MSG_SIZ, "%s vs. %s", gameInfo.white, gameInfo.black);
     DisplayTitle(buf);
     if (first.sendName) {
-      sprintf(buf, "name %s\n", gameInfo.white);
+      snprintf(buf, MSG_SIZ, "name %s\n", gameInfo.white);
       SendToProgram(buf, &first);
     }
     if (first.sendTime) {
@@ -11722,18 +11761,18 @@ DisplayTwoMachinesTitle()
     char buf[MSG_SIZ];
     if (appData.matchGames > 0) {
         if (first.twoMachinesColor[0] == 'w') {
-           sprintf(buf, "%s vs. %s (%d-%d-%d)",
-                   gameInfo.white, gameInfo.black,
-                   first.matchWins, second.matchWins,
-                   matchGame - 1 - (first.matchWins + second.matchWins));
+         snprintf(buf, MSG_SIZ, "%s vs. %s (%d-%d-%d)",
+                  gameInfo.white, gameInfo.black,
+                  first.matchWins, second.matchWins,
+                  matchGame - 1 - (first.matchWins + second.matchWins));
        } else {
-           sprintf(buf, "%s vs. %s (%d-%d-%d)",
-                   gameInfo.white, gameInfo.black,
-                   second.matchWins, first.matchWins,
-                   matchGame - 1 - (first.matchWins + second.matchWins));
+         snprintf(buf, MSG_SIZ, "%s vs. %s (%d-%d-%d)",
+                  gameInfo.white, gameInfo.black,
+                  second.matchWins, first.matchWins,
+                  matchGame - 1 - (first.matchWins + second.matchWins));
        }
     } else {
-       sprintf(buf, "%s vs. %s", gameInfo.white, gameInfo.black);
+      snprintf(buf, MSG_SIZ, "%s vs. %s", gameInfo.white, gameInfo.black);
     }
     DisplayTitle(buf);
 }
@@ -11819,12 +11858,12 @@ TwoMachinesEvent P((void))
 
     SendToProgram(first.computerString, &first);
     if (first.sendName) {
-      sprintf(buf, "name %s\n", second.tidy);
+      snprintf(buf, MSG_SIZ, "name %s\n", second.tidy);
       SendToProgram(buf, &first);
     }
     SendToProgram(second.computerString, &second);
     if (second.sendName) {
-      sprintf(buf, "name %s\n", first.tidy);
+      snprintf(buf, MSG_SIZ, "name %s\n", first.tidy);
       SendToProgram(buf, &second);
     }
 
@@ -12183,7 +12222,7 @@ EditPositionMenuEvent(selection, x, y)
                 for (y = 0; y < BOARD_HEIGHT; y++) {
                    if (gameMode == IcsExamining) {
                        if (boards[currentMove][y][x] != EmptySquare) {
-                           sprintf(buf, "%sx@%c%c\n", ics_prefix,
+                         snprintf(buf, MSG_SIZ, "%sx@%c%c\n", ics_prefix,
                                     AAA + x, ONE + y);
                            SendToICS(buf);
                        }
@@ -12209,7 +12248,7 @@ EditPositionMenuEvent(selection, x, y)
       case EmptySquare:
        if (gameMode == IcsExamining) {
             if (x < BOARD_LEFT || x >= BOARD_RGHT) break; // [HGM] holdings
-            sprintf(buf, "%sx@%c%c\n", ics_prefix, AAA + x, ONE + y);
+            snprintf(buf, MSG_SIZ, "%sx@%c%c\n", ics_prefix, AAA + x, ONE + y);
            SendToICS(buf);
        } else {
             if(x < BOARD_LEFT || x >= BOARD_RGHT) {
@@ -12262,8 +12301,8 @@ EditPositionMenuEvent(selection, x, y)
         defaultlabel:
        if (gameMode == IcsExamining) {
             if (x < BOARD_LEFT || x >= BOARD_RGHT) break; // [HGM] holdings
-           sprintf(buf, "%s%c@%c%c\n", ics_prefix,
-                    PieceToChar(selection), AAA + x, ONE + y);
+           snprintf(buf, MSG_SIZ, "%s%c@%c%c\n", ics_prefix,
+                    PieceToChar(selection), AAA + x, ONE + y);
            SendToICS(buf);
        } else {
             if(x < BOARD_LEFT || x >= BOARD_RGHT) {
@@ -13020,11 +13059,11 @@ TimeControlTagValue()
     if (!appData.clockMode) {
       safeStrCpy(buf, "-", sizeof(buf)/sizeof(buf[0]));
     } else if (movesPerSession > 0) {
-      sprintf(buf, "%d/%ld", movesPerSession, timeControl/1000);
+      snprintf(buf, MSG_SIZ, "%d/%ld", movesPerSession, timeControl/1000);
     } else if (timeIncrement == 0) {
-      sprintf(buf, "%ld", timeControl/1000);
+      snprintf(buf, MSG_SIZ, "%ld", timeControl/1000);
     } else {
-      sprintf(buf, "%ld+%ld", timeControl/1000, timeIncrement/1000);
+      snprintf(buf, MSG_SIZ, "%ld+%ld", timeControl/1000, timeIncrement/1000);
     }
     return StrSave(buf);
 }
@@ -13072,7 +13111,7 @@ SetGameInfo()
        gameInfo.date = PGNDate();
        if (matchGame > 0) {
            char buf[MSG_SIZ];
-           sprintf(buf, "%d", matchGame);
+           snprintf(buf, MSG_SIZ, "%d", matchGame);
            gameInfo.round = StrSave(buf);
        } else {
            gameInfo.round = StrSave("-");
@@ -13348,11 +13387,11 @@ SendToProgram(message, cps)
     outCount = OutputToProcess(cps->pr, message, count, &error);
     if (outCount < count && !exiting
                          && !endingGame) { /* [HGM] crash: to not hang GameEnds() writing to deceased engines */
-       sprintf(buf, _("Error writing to %s chess program"), cps->which);
+      snprintf(buf, MSG_SIZ, _("Error writing to %s chess program"), cps->which);
         if(gameInfo.resultDetails==NULL) { /* [HGM] crash: if game in progress, give reason for abort */
             if((signed char)boards[forwardMostMove][EP_STATUS] <= EP_DRAWS) {
                 gameInfo.result = GameIsDrawn; /* [HGM] accept exit as draw claim */
-                sprintf(buf, "%s program exits in draw position (%s)", cps->which, cps->program);
+                snprintf(buf, MSG_SIZ, "%s program exits in draw position (%s)", cps->which, cps->program);
             } else {
                 gameInfo.result = cps->twoMachinesColor[0]=='w' ? BlackWins : WhiteWins;
             }
@@ -13377,13 +13416,12 @@ ReceiveFromProgram(isr, closure, message, count, error)
     if (isr != cps->isr) return; /* Killed intentionally */
     if (count <= 0) {
        if (count == 0) {
-           sprintf(buf,
-                   _("Error: %s chess program (%s) exited unexpectedly"),
+           snprintf(buf, MSG_SIZ, _("Error: %s chess program (%s) exited unexpectedly"),
                    cps->which, cps->program);
         if(gameInfo.resultDetails==NULL) { /* [HGM] crash: if game in progress, give reason for abort */
                 if((signed char)boards[forwardMostMove][EP_STATUS] <= EP_DRAWS) {
                     gameInfo.result = GameIsDrawn; /* [HGM] accept exit as draw claim */
-                    sprintf(buf, _("%s program exits in draw position (%s)"), cps->which, cps->program);
+                    snprintf(buf, MSG_SIZ, _("%s program exits in draw position (%s)"), cps->which, cps->program);
                 } else {
                     gameInfo.result = cps->twoMachinesColor[0]=='w' ? BlackWins : WhiteWins;
                 }
@@ -13392,8 +13430,7 @@ ReceiveFromProgram(isr, closure, message, count, error)
            RemoveInputSource(cps->isr);
            if(!cps->userError || !appData.popupExitMessage) DisplayFatalError(buf, 0, 1); else errorExitStatus = 1;
        } else {
-           sprintf(buf,
-                   _("Error reading from %s chess program (%s)"),
+           snprintf(buf, MSG_SIZ, _("Error reading from %s chess program (%s)"),
                    cps->which, cps->program);
            RemoveInputSource(cps->isr);
 
@@ -13478,12 +13515,12 @@ SendTimeControl(cps, mps, tc, inc, sd, st)
        /* GNU Chess 4 has no st command; uses level in a nonstandard way */
        seconds = st % 60;
        if (seconds == 0) {
-         sprintf(buf, "level 1 %d\n", st/60);
+         snprintf(buf, MSG_SIZ, "level 1 %d\n", st/60);
        } else {
-         sprintf(buf, "level 1 %d:%02d\n", st/60, seconds);
+         snprintf(buf, MSG_SIZ, "level 1 %d:%02d\n", st/60, seconds);
        }
       } else {
-       sprintf(buf, "st %d\n", st);
+       snprintf(buf, MSG_SIZ, "st %d\n", st);
       }
     } else {
       /* Set conventional or incremental time control, using level command */
@@ -13491,10 +13528,10 @@ SendTimeControl(cps, mps, tc, inc, sd, st)
        /* Note old gnuchess bug -- minutes:seconds used to not work.
           Fixed in later versions, but still avoid :seconds
           when seconds is 0. */
-       sprintf(buf, "level %d %ld %d\n", mps, tc/60000, inc/1000);
+       snprintf(buf, MSG_SIZ, "level %d %ld %d\n", mps, tc/60000, inc/1000);
       } else {
-       sprintf(buf, "level %d %ld:%02d %d\n", mps, tc/60000,
-               seconds, inc/1000);
+       snprintf(buf, MSG_SIZ, "level %d %ld:%02d %d\n", mps, tc/60000,
+                seconds, inc/1000);
       }
     }
     SendToProgram(buf, cps);
@@ -13503,18 +13540,19 @@ SendTimeControl(cps, mps, tc, inc, sd, st)
     /* Orthogonally, limit search to given depth */
     if (sd > 0) {
       if (cps->sdKludge) {
-       sprintf(buf, "depth\n%d\n", sd);
+       snprintf(buf, MSG_SIZ, "depth\n%d\n", sd);
       } else {
-       sprintf(buf, "sd %d\n", sd);
+       snprintf(buf, MSG_SIZ, "sd %d\n", sd);
       }
       SendToProgram(buf, cps);
     }
 
     if(cps->nps > 0) { /* [HGM] nps */
-       if(cps->supportsNPS == FALSE) cps->nps = -1; // don't use if engine explicitly says not supported!
+       if(cps->supportsNPS == FALSE)
+         cps->nps = -1; // don't use if engine explicitly says not supported!
        else {
-               sprintf(buf, "nps %d\n", cps->nps);
-             SendToProgram(buf, cps);
+         snprintf(buf, MSG_SIZ, "nps %d\n", cps->nps);
+         SendToProgram(buf, cps);
        }
     }
 }
@@ -13556,10 +13594,10 @@ SendTimeRemaining(cps, machineWhite)
     if (time <= 0) time = 1;
     if (otime <= 0) otime = 1;
 
-    sprintf(message, "time %ld\n", time);
+    snprintf(message, MSG_SIZ, "time %ld\n", time);
     SendToProgram(message, cps);
 
-    sprintf(message, "otim %ld\n", otime);
+    snprintf(message, MSG_SIZ, "otim %ld\n", otime);
     SendToProgram(message, cps);
 }
 
@@ -13573,12 +13611,14 @@ BoolFeature(p, name, loc, cps)
   char buf[MSG_SIZ];
   int len = strlen(name);
   int val;
+
   if (strncmp((*p), name, len) == 0 && (*p)[len] == '=') {
     (*p) += len + 1;
     sscanf(*p, "%d", &val);
     *loc = (val != 0);
-    while (**p && **p != ' ') (*p)++;
-    sprintf(buf, "accepted %s\n", name);
+    while (**p && **p != ' ')
+      (*p)++;
+    snprintf(buf, MSG_SIZ, "accepted %s\n", name);
     SendToProgram(buf, cps);
     return TRUE;
   }
@@ -13598,7 +13638,7 @@ IntFeature(p, name, loc, cps)
     (*p) += len + 1;
     sscanf(*p, "%d", loc);
     while (**p && **p != ' ') (*p)++;
-    sprintf(buf, "accepted %s\n", name);
+    snprintf(buf, MSG_SIZ, "accepted %s\n", name);
     SendToProgram(buf, cps);
     return TRUE;
   }
@@ -13620,7 +13660,7 @@ StringFeature(p, name, loc, cps)
     sscanf(*p, "%[^\"]", loc);
     while (**p && **p != '\"') (*p)++;
     if (**p == '\"') (*p)++;
-    sprintf(buf, "accepted %s\n", name);
+    snprintf(buf, MSG_SIZ, "accepted %s\n", name);
     SendToProgram(buf, cps);
     return TRUE;
   }
@@ -13696,7 +13736,7 @@ ParseOption(Option *opt, ChessProgramState *cps)
        if(cps->optionSettings && cps->optionSettings[0])
            p = strstr(cps->optionSettings, opt->name); else p = NULL;
        if(p && (p == cps->optionSettings || p[-1] == ',')) {
-               sprintf(buf, "option %s", p);
+         snprintf(buf, MSG_SIZ, "option %s", p);
                if(p = strstr(buf, ",")) *p = 0;
                strcat(buf, "\n");
                SendToProgram(buf, cps);
@@ -13779,13 +13819,13 @@ ParseFeatures(args, cps)
     if (StringFeature(&p, "egt", &cps->egtFormats, cps)) continue;
     if (StringFeature(&p, "option", &(cps->option[cps->nrOptions].name), cps)) {
        if(!ParseOption(&(cps->option[cps->nrOptions++]), cps)) { // [HGM] options: add option feature
-           sprintf(buf, "rejected option %s\n", cps->option[--cps->nrOptions].name);
+         snprintf(buf, MSG_SIZ, "rejected option %s\n", cps->option[--cps->nrOptions].name);
            SendToProgram(buf, cps);
            continue;
        }
        if(cps->nrOptions >= MAX_OPTIONS) {
            cps->nrOptions--;
-           sprintf(buf, "%s engine has too many options\n", cps->which);
+           snprintf(buf, MSG_SIZ, "%s engine has too many options\n", cps->which);
            DisplayError(buf, 0);
        }
        continue;
@@ -13795,7 +13835,7 @@ ParseFeatures(args, cps)
     /* unknown feature: complain and skip */
     q = p;
     while (*q && *q != '=') q++;
-    sprintf(buf, "rejected %.*s\n", (int)(q-p), p);
+    snprintf(buf, MSG_SIZ,"rejected %.*s\n", (int)(q-p), p);
     SendToProgram(buf, cps);
     p = q;
     if (*p == '=') {
@@ -13860,7 +13900,7 @@ NewSettingEvent(option, feature, command, value)
     char buf[MSG_SIZ];
 
     if (gameMode == EditPosition) EditPositionDone(TRUE);
-    sprintf(buf, "%s%s %d\n", (option ? "option ": ""), command, value);
+    snprintf(buf, MSG_SIZ,"%s%s %d\n", (option ? "option ": ""), command, value);
     if(feature == NULL || *feature) SendToProgram(buf, &first);
     if (gameMode == TwoMachinesPlay) {
        if(feature == NULL || feature[(int*)&second - (int*)&first]) SendToProgram(buf, &second);
@@ -13942,9 +13982,9 @@ DisplayMove(moveNumber)
     if (moveNumber == forwardMostMove - 1 &&
        gameInfo.resultDetails != NULL) {
        if (gameInfo.resultDetails[0] == NULLCHAR) {
-           sprintf(res, " %s", PGNResult(gameInfo.result));
+         snprintf(res, MSG_SIZ, " %s", PGNResult(gameInfo.result));
        } else {
-           sprintf(res, " {%s} %s",
+         snprintf(res, MSG_SIZ, " {%s} %s",
                    T_(gameInfo.resultDetails), PGNResult(gameInfo.result));
        }
     } else {
@@ -13954,7 +13994,7 @@ DisplayMove(moveNumber)
     if (moveNumber < 0 || parseList[moveNumber][0] == NULLCHAR) {
        DisplayMessage(res, cpThinkOutput);
     } else {
-       sprintf(message, "%d.%s%s%s", moveNumber / 2 + 1,
+      snprintf(message, MSG_SIZ, "%d.%s%s%s", moveNumber / 2 + 1,
                WhiteOnMove(moveNumber) ? " " : ".. ",
                parseList[moveNumber], res);
        DisplayMessage(message, cpThinkOutput);
@@ -13973,7 +14013,7 @@ DisplayComment(moveNumber, text)
     if (moveNumber < 0 || parseList[moveNumber][0] == NULLCHAR) {
       safeStrCpy(title, "Comment", sizeof(title)/sizeof(title[0]));
     } else {
-      sprintf(title, "Comment on %d.%s%s", moveNumber / 2 + 1,
+      snprintf(title,MSG_SIZ, "Comment on %d.%s%s", moveNumber / 2 + 1,
              WhiteOnMove(moveNumber) ? " " : ".. ",
              parseList[moveNumber]);
     }
@@ -13981,7 +14021,7 @@ DisplayComment(moveNumber, text)
     if(moveNumber >= 0 && (depth = pvInfoList[moveNumber].depth) > 0) {
       if(text == NULL) text = "";
       score = pvInfoList[moveNumber].score;
-      sprintf(buf, "%s%.2f/%d %d\n%s", score>0 ? "+" : "", score/100.,
+      snprintf(buf,sizeof(buf)/sizeof(buf[0]), "%s%.2f/%d %d\n%s", score>0 ? "+" : "", score/100.,
              depth, (pvInfoList[moveNumber].time+50)/100, text);
       text = buf;
     }
@@ -14438,7 +14478,7 @@ TimeString(ms)
       /* convert milliseconds to tenths, rounding up */
       double tenths = floor( ((double)(ms + 99L)) / 100.00 );
 
-      sprintf(buf, " %03.1f ", tenths/10.0);
+      snprintf(buf,sizeof(buf)/sizeof(buf[0]), " %03.1f ", tenths/10.0);
       return buf;
     }
 
@@ -14460,12 +14500,12 @@ TimeString(ms)
     second = second % 60;
 
     if (day > 0)
-      sprintf(buf, " %s%ld:%02ld:%02ld:%02ld ",
+      snprintf(buf, sizeof(buf)/sizeof(buf[0]), " %s%ld:%02ld:%02ld:%02ld ",
              sign, day, hour, minute, second);
     else if (hour > 0)
-      sprintf(buf, " %s%ld:%02ld:%02ld ", sign, hour, minute, second);
+      snprintf(buf, sizeof(buf)/sizeof(buf[0]), " %s%ld:%02ld:%02ld ", sign, hour, minute, second);
     else
-      sprintf(buf, " %s%2ld:%02ld ", sign, minute, second);
+      snprintf(buf, sizeof(buf)/sizeof(buf[0]), " %s%2ld:%02ld ", sign, minute, second);
 
     return buf;
 }
@@ -14576,7 +14616,7 @@ PGNDate()
 
     clock = time((time_t *)NULL);
     tm = localtime(&clock);
-    sprintf(buf, "%04d.%02d.%02d",
+    snprintf(buf, MSG_SIZ, "%04d.%02d.%02d",
            tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday);
     return StrSave(buf);
 }
@@ -15178,12 +15218,13 @@ PopTail(Boolean annotate)
        nrMoves = savedLast[storedGames] - currentMove;
        if(annotate) {
                int cnt = 10;
-               if(!WhiteOnMove(currentMove)) sprintf(buf, "(%d...", currentMove+2>>1);
+               if(!WhiteOnMove(currentMove))
+                 snprintf(buf, sizeof(buf)/sizeof(buf[0]),"(%d...", currentMove+2>>1);
                else safeStrCpy(buf, "(", sizeof(buf)/sizeof(buf[0]));
                for(i=currentMove; i<forwardMostMove; i++) {
                        if(WhiteOnMove(i))
-                            sprintf(moveBuf, " %d. %s", i+2>>1, SavePart(parseList[i]));
-                       else sprintf(moveBuf, " %s", SavePart(parseList[i]));
+                         snprintf(moveBuf, sizeof(moveBuf)/sizeof(moveBuf[0]), " %d. %s", i+2>>1, SavePart(parseList[i]));
+                       else snprintf(moveBuf, sizeof(moveBuf)/sizeof(moveBuf[0])," %s", SavePart(parseList[i]));
                        strcat(buf, moveBuf);
                        if(commentList[i]) { strcat(buf, " "); strcat(buf, commentList[i]); }
                        if(!--cnt) { strcat(buf, "\n"); cnt = 10; }
index e0de2b6..31512a8 100644 (file)
--- a/childio.c
+++ b/childio.c
@@ -209,7 +209,7 @@ int PseudoTTY(pty_name)
 #ifdef PTY_NAME_SPRINTF
        PTY_NAME_SPRINTF
 #else
-       sprintf (pty_name, "/dev/pty%c%x", c, i);
+         sprintf (pty_name, "/dev/pty%c%x", c, i);
 #endif /* no PTY_NAME_SPRINTF */
 
 #ifdef PTY_OPEN
@@ -233,7 +233,7 @@ int PseudoTTY(pty_name)
 #ifdef PTY_TTY_NAME_SPRINTF
            PTY_TTY_NAME_SPRINTF
 #else
-            sprintf (pty_name, "/dev/tty%c%x", c, i);
+             sprintf (pty_name,  "/dev/tty%c%x", c, i);
 #endif /* no PTY_TTY_NAME_SPRINTF */
 #ifndef UNIPLUS
            if (access (pty_name, 6) != 0)
index cf17e41..22b008c 100644 (file)
@@ -349,7 +349,7 @@ static void UpdateControls( EngineOutputData * ed )
 //    int isPondering = FALSE;
 
     char s_label[MAX_NAME_LENGTH + 32];
-    
+
     char * name = ed->name;
 
     /* Label */
@@ -402,7 +402,7 @@ static void UpdateControls( EngineOutputData * ed )
             strncpy( mov, ed->hint, sizeof(mov) );
             mov[ sizeof(mov)-1 ] = '\0';
 
-            sprintf( buf, "[%d] %d/%d: %s [%02d:%02d:%02d]", ed->depth, ed->an_move_index,
+            snprintf( buf, sizeof(buf)/sizeof(buf[0]), "[%d] %d/%d: %s [%02d:%02d:%02d]", ed->depth, ed->an_move_index,
                        ed->an_move_count, mov, time_mins / 60, time_mins % 60, time_secs % 60 );
         }
 
@@ -421,10 +421,10 @@ static void UpdateControls( EngineOutputData * ed )
         unsigned long nps_100 = ed->nodes / ed->time;
 
         if( nps_100 < 100000 ) {
-            sprintf( s_label, "NPS: %lu", nps_100 * 100 );
+         snprintf( s_label, sizeof(s_label)/sizeof(s_label[0]), "NPS: %lu", nps_100 * 100 );
         }
         else {
-            sprintf( s_label, "NPS: %.1fk", nps_100 / 10.0 );
+         snprintf( s_label, sizeof(s_label)/sizeof(s_label[0]), "NPS: %.1fk", nps_100 / 10.0 );
         }
     }
 
@@ -442,26 +442,28 @@ static void UpdateControls( EngineOutputData * ed )
 
         /* Nodes */
         if( ed->nodes < 1000000 ) {
-            sprintf( s_nodes, u64Display, ed->nodes );
+            snprintf( s_nodes, sizeof(s_nodes)/sizeof(s_nodes[0]), u64Display, ed->nodes );
         }
         else {
-            sprintf( s_nodes, "%.1fM", u64ToDouble(ed->nodes) / 1000000.0 );
+            snprintf( s_nodes, sizeof(s_nodes)/sizeof(s_nodes[0]), "%.1fM", u64ToDouble(ed->nodes) / 1000000.0 );
         }
 
         /* Score */
         if( ed->score > 0 ) {
-            sprintf( s_score, "+%.2f", ed->score / 100.0 );
+         snprintf( s_score, sizeof(s_score)/sizeof(s_score[0]), "+%.2f", ed->score / 100.0 );
         }
         else {
-            sprintf( s_score, "%.2f", ed->score / 100.0 );
+         snprintf( s_score, sizeof(s_score)/sizeof(s_score[0]), "%.2f", ed->score / 100.0 );
         }
 
         /* Time */
-        sprintf( s_time, "%d:%02d.%02d", time_secs / 60, time_secs % 60, time_cent );
+        snprintf( s_time, sizeof(s_time)/sizeof(s_time[0]), "%d:%02d.%02d", time_secs / 60, time_secs % 60, time_cent );
 
         /* Put all together... */
-       if(ed->nodes == 0 && ed->score == 0 && ed->time == 0) sprintf( buf, "%3d\t", ed->depth ); else 
-       sprintf( buf, "%3d\t%s\t%s\t%s\t", ed->depth, s_score, s_nodes, s_time );
+       if(ed->nodes == 0 && ed->score == 0 && ed->time == 0)
+         snprintf( buf, sizeof(buf)/sizeof(buf[0]), "%3d\t", ed->depth );
+       else
+         snprintf( buf, sizeof(buf)/sizeof(buf[0]), "%3d\t%s\t%s\t%s\t", ed->depth, s_score, s_nodes, s_time );
 
         /* Add PV */
         buflen = strlen(buf);
index 07619f2..028b961 100644 (file)
@@ -435,7 +435,7 @@ char * GameListLine( int number, GameInfo * gameInfo )
             break;
         case GLT_WHITE_ELO:
             if( gameInfo->whiteRating > 0 )
-                sprintf( buf, "%d", gameInfo->whiteRating );
+             sprintf( buf,  "%d", gameInfo->whiteRating );
             else
              safeStrCpy( buf, "?" , 2*MSG_SIZ);
             break;
index 0a70df2..82dfc1d 100644 (file)
--- a/pgntags.c
+++ b/pgntags.c
@@ -155,41 +155,41 @@ static char *PGNTagsStatic(gameInfo)
 
     buf[0] = NULLCHAR;
 
-    sprintf(buf1, "[Event \"%s\"]\n",
+    snprintf(buf1, MSG_SIZ, "[Event \"%s\"]\n",
            gameInfo->event ? gameInfo->event : "?");
     strcat(buf, buf1);
-    sprintf(buf1, "[Site \"%s\"]\n",
+    snprintf(buf1, MSG_SIZ, "[Site \"%s\"]\n",
            gameInfo->site ? gameInfo->site : "?");
     strcat(buf, buf1);
-    sprintf(buf1, "[Date \"%s\"]\n",
+    snprintf(buf1, MSG_SIZ, "[Date \"%s\"]\n",
            gameInfo->date ? gameInfo->date : "?");
     strcat(buf, buf1);
-    sprintf(buf1, "[Round \"%s\"]\n",
+    snprintf(buf1, MSG_SIZ, "[Round \"%s\"]\n",
            gameInfo->round ? gameInfo->round : "-");
     strcat(buf, buf1);
-    sprintf(buf1, "[White \"%s\"]\n",
+    snprintf(buf1, MSG_SIZ, "[White \"%s\"]\n",
            gameInfo->white ? gameInfo->white : "?");
     strcat(buf, buf1);
-    sprintf(buf1, "[Black \"%s\"]\n",
+    snprintf(buf1, MSG_SIZ, "[Black \"%s\"]\n",
            gameInfo->black ? gameInfo->black : "?");
     strcat(buf, buf1);
-    sprintf(buf1, "[Result \"%s\"]\n", PGNResult(gameInfo->result));
+    snprintf(buf1, MSG_SIZ, "[Result \"%s\"]\n", PGNResult(gameInfo->result));
     strcat(buf, buf1);
+
     if (gameInfo->whiteRating >= 0 ) {
-       sprintf(buf1, "[WhiteElo \"%d\"]\n", gameInfo->whiteRating );
+       snprintf(buf1, MSG_SIZ, "[WhiteElo \"%d\"]\n", gameInfo->whiteRating );
        strcat(buf, buf1);
     }
     if ( gameInfo->blackRating >= 0 ) {
-       sprintf(buf1, "[BlackElo \"%d\"]\n", gameInfo->blackRating );
+       snprintf(buf1, MSG_SIZ, "[BlackElo \"%d\"]\n", gameInfo->blackRating );
        strcat(buf, buf1);
-    }    
+    }
     if (gameInfo->timeControl != NULL) {
-       sprintf(buf1, "[TimeControl \"%s\"]\n", gameInfo->timeControl);
+       snprintf(buf1, MSG_SIZ, "[TimeControl \"%s\"]\n", gameInfo->timeControl);
        strcat(buf, buf1);
     }
     if (gameInfo->variant != VariantNormal) {
-        sprintf(buf1, "[Variant \"%s\"]\n", VariantName(gameInfo->variant));
+        snprintf(buf1, MSG_SIZ, "[Variant \"%s\"]\n", VariantName(gameInfo->variant));
        strcat(buf, buf1);
     }
     if (gameInfo->extraTags != NULL) {
@@ -199,7 +199,7 @@ static char *PGNTagsStatic(gameInfo)
 }
 
 
+
 /* Print game info
  */
 void PrintPGNTags(fp, gameInfo)
@@ -235,7 +235,7 @@ char *PGNResult(result)
       case GameIsDrawn:
        return "1/2-1/2";
     }
-}  
+}
 
 /* Returns 0 for success, nonzero for error */
 int
@@ -256,7 +256,7 @@ ReplaceTags(tags, gameInfo)
        } else if (moveType == PGNTag) {
            err = ParsePGNTag(yy_text, gameInfo);
            if (err != 0) return err;
-       } 
+       }
     }
     /* just one problem...if there is a result in the new tags,
      * DisplayMove() won't ever show it because ClearGameInfo() set
index 2a82f91..f2c3afa 100644 (file)
@@ -9,8 +9,8 @@
 \r
 \r
 int sizeList[] = { 21, 25, 29, 33, 37, 40, 45, 49, 54, 58, 64, 72, 80, 87, 95, 108, 116, 129 };\r
-char *(pieceList[]) = {"p", "n", "b", "r", "q", "f", "e", "as", "c", "w", "m", \r
-                      "o", "h", "a", "dk", "g", "d", "v", "l", "s", "u", "k", \r
+char *(pieceList[]) = {"p", "n", "b", "r", "q", "f", "e", "as", "c", "w", "m",\r
+                      "o", "h", "a", "dk", "g", "d", "v", "l", "s", "u", "k",\r
                       "wp", "wl", "wn", "ws", "cv", NULL };\r
 char kindList[] = "sow";\r
 \r
@@ -64,7 +64,7 @@ FloodFill(char a[130][130], int size, int x, int y)
                if(x < size-1) FloodFill(a, size, x+1, y);\r
                if(y < size-1) FloodFill(a, size, x, y+1);\r
        }\r
-       \r
+\r
 }\r
 \r
 void Save(FILE *f, char *name, char data[130][130], int size, char *col, int depth)\r
@@ -92,7 +92,10 @@ char data[130][130], oData[130][130], sData[130][130], wData[130][130];
 \r
 main(int argc, char **argv)\r
 {\r
-       int i, j, k, d, cnt, p, s, t; char c, h, w, name[80], buf[80], transparent;\r
+\r
+#define BUFLEN 80\r
+\r
+       int i, j, k, d, cnt, p, s, t; char c, h, w, name[BUFLEN], buf[BUFLEN], transparent;\r
        FILE *f;\r
 \r
     transparent = argc > 1 && !strcmp(argv[1], "-t");\r
@@ -101,20 +104,20 @@ main(int argc, char **argv)
 \r
        // Load the 3 kinds of Windows monochrome bitmaps (outline, solid, white fill)\r
 \r
-       sprintf(buf, "../winboard/bitmaps/%s%d%c.bmp", pieceList[p], sizeList[s], 'o');\r
+       snprintf(buf, BUFLEN, "../winboard/bitmaps/%s%d%c.bmp", pieceList[p], sizeList[s], 'o');\r
        printf("try %s\n", buf);\r
        f = fopen(buf, "rb");\r
        if(f == NULL) continue;\r
        Load(f, oData, buf);\r
 \r
-       sprintf(buf, "../winboard/bitmaps/%s%d%c.bmp", pieceList[p], sizeList[s], 's');\r
+       snprintf(buf, BUFLEN, "../winboard/bitmaps/%s%d%c.bmp", pieceList[p], sizeList[s], 's');\r
        f = fopen(buf, "rb");\r
        if(f == NULL) continue;\r
        Load(f, sData, buf);\r
 \r
-       sprintf(buf, "../winboard/bitmaps/%s%d%c.bmp", pieceList[p], sizeList[s], 'w');\r
+       snprintf(buf, BUFLEN, "../winboard/bitmaps/%s%d%c.bmp", pieceList[p], sizeList[s], 'w');\r
        if(pieceList[p][0]=='w')\r
-       sprintf(buf, "../winboard/bitmaps/%s%d%c.bmp", "w", sizeList[s], 'w');\r
+       snprintf(buf, BUFLEN, "../winboard/bitmaps/%s%d%c.bmp", "w", sizeList[s], 'w');\r
        f = fopen(buf, "rb");\r
        if(f == NULL) continue;\r
        Load(f, wData, buf);\r
@@ -133,13 +136,13 @@ main(int argc, char **argv)
            FloodFill(data, d, d-1, d-1);\r
        }\r
 \r
-       sprintf(buf, "%s%s%d.xpm", pieceList[p], "dd", d);\r
-       sprintf(name, "%s%s%d", pieceList[p], "dd", d);\r
+       snprintf(buf, BUFLEN, "%s%s%d.xpm", pieceList[p], "dd", d);\r
+       snprintf(name, BUFLEN, "%s%s%d", pieceList[p], "dd", d);\r
        f = fopen(buf, "w");\r
        Save(f, name, data, d, "c green s dark_square", 3);\r
 \r
-       sprintf(buf, "%s%s%d.xpm", pieceList[p], "dl", d);\r
-       sprintf(name, "%s%s%d", pieceList[p], "dl", d);\r
+       snprintf(buf, BUFLEN, "%s%s%d.xpm", pieceList[p], "dl", d);\r
+       snprintf(name, BUFLEN, "%s%s%d", pieceList[p], "dl", d);\r
        f = fopen(buf, "w");\r
        Save(f, name, data, d, "c gray s light_square", 3); // silly duplication; pixmap is te same, but other color\r
 \r
@@ -149,13 +152,13 @@ main(int argc, char **argv)
        Paint(data, wData, d, 'X'); // overay with white-filler piece bitmap\r
        Paint(data, oData, d, ' '); // overay with outline piece bitmaps\r
 \r
-       sprintf(buf, "%s%s%d.xpm", pieceList[p], "ld", d);\r
-       sprintf(name, "%s%s%d", pieceList[p], "ld", d);\r
+       snprintf(buf, BUFLEN, "%s%s%d.xpm", pieceList[p], "ld", d);\r
+       snprintf(name, BUFLEN, "%s%s%d", pieceList[p], "ld", d);\r
        f = fopen(buf, "w");\r
        Save(f, name, data, d, "c green s dark_square", 3);\r
 \r
-       sprintf(buf, "%s%s%d.xpm", pieceList[p], "ll", d);\r
-       sprintf(name, "%s%s%d", pieceList[p], "ll", d);\r
+       snprintf(buf, BUFLEN, "%s%s%d.xpm", pieceList[p], "ll", d);\r
+       snprintf(name, BUFLEN, "%s%s%d", pieceList[p], "ll", d);\r
        f = fopen(buf, "w");\r
        Save(f, name, data, d, "c gray s light_square", 3);\r
 \r
index 228e493..b114497 100644 (file)
@@ -60,7 +60,7 @@ HtmlHelp( HWND hwnd, LPCSTR helpFile, UINT action, DWORD_PTR data )
        siStartInfo.hStdOutput = NULL;\r
        siStartInfo.hStdError = debugFP;\r
 \r
-       sprintf(buf, "Hh.exe %s", helpFile);\r
+       snprintf(buf, sizeof(buf)/sizeof(buf[0]),"Hh.exe %s", helpFile);\r
 \r
        // ignore the other parameters; just start the viewer with the help file\r
        if(  CreateProcess(NULL,\r
index 8d7e42c..da9950d 100644 (file)
@@ -92,7 +92,7 @@ char *squareToNum[] = {"naught", "1", "2", "3", "4", "5", "6", "7", "8", "9" };
 char *ordinals[] = {"zeroth", "first", "second", "third", "fourth", "fifth", "sixth", "seventh", "eighth", "nineth"};\r
 \r
 char *pieceToName[] = {\r
-               "White Pawn", "White Knight", "White Bishop", "White Rook", "White Queen", \r
+               "White Pawn", "White Knight", "White Bishop", "White Rook", "White Queen",\r
                "White Guard", "White Elephant", "White Arch Bishop", "White Chancellor",\r
                "White General", "White Man", "White Cannon", "White Night Rider",\r
                "White Crowned Bishop", "White Crowned Rook", "White Grass Hopper", "White Veteran",\r
@@ -108,13 +108,13 @@ char *pieceToName[] = {
        };\r
 \r
 char *pieceTypeName[] = {\r
-               "Pawn", "Knight", "Bishop", "Rook", "Queen", \r
+               "Pawn", "Knight", "Bishop", "Rook", "Queen",\r
                "Guard", "Elephant", "Arch Bishop", "Chancellor",\r
                "General", "Man", "Cannon", "Night Rider",\r
                "Crowned Bishop", "Crowned Rook", "Grass Hopper", "Veteran",\r
                "Falcon", "Amazon", "Snake", "Unicorn",\r
                "King",\r
-               "Pawn", "Knight", "Bishop", "Rook", "Queen", \r
+               "Pawn", "Knight", "Bishop", "Rook", "Queen",\r
                "Guard", "Elephant", "Arch Bishop", "Chancellor",\r
                "General", "Man", "Cannon", "Night Rider",\r
                "Crowned Bishop", "Crowned Rook", "Grass Hopper", "Veteran",\r
@@ -230,14 +230,14 @@ AdaptMenu()
        helpMenuInfo.cbSize = sizeof(helpMenuInfo);\r
        menuMain = GetMenu(hwndMain);\r
        menuJAWS = CreatePopupMenu();\r
-       \r
+\r
        for(i=0; menuItemJAWS[i].name; i++) {\r
-           if(menuItemJAWS[i].name[0] == '-') \r
+           if(menuItemJAWS[i].name[0] == '-')\r
                 AppendMenu(menuJAWS, MF_SEPARATOR, (UINT_PTR) 0, NULL);\r
-           else AppendMenu(menuJAWS, MF_ENABLED|MF_STRING, \r
+           else AppendMenu(menuJAWS, MF_ENABLED|MF_STRING,\r
                        (UINT_PTR) menuItemJAWS[i].code, (LPCTSTR) menuItemJAWS[i].name);\r
        }\r
-       InsertMenu(menuMain, 5, MF_BYPOSITION|MF_POPUP|MF_ENABLED|MF_STRING, \r
+       InsertMenu(menuMain, 5, MF_BYPOSITION|MF_POPUP|MF_ENABLED|MF_STRING,\r
                (UINT_PTR) menuJAWS, "&JAWS");\r
        oldMenuItemState[6] = oldMenuItemState[5];\r
        DrawMenuBar(hwndMain);\r
@@ -248,7 +248,7 @@ InitJAWS()
 {      // to be called at beginning of WinMain, after InitApplication and InitInstance\r
        HINSTANCE hApi = LoadLibrary("jfwapi32.dll");\r
        if(!hApi) {\r
-               DisplayInformation("Missing jfwapi32.dll");        \r
+               DisplayInformation("Missing jfwapi32.dll");\r
                return (FALSE);\r
        }\r
 \r
@@ -331,7 +331,7 @@ KeyboardEvent(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
                if(currentPiece != EmptySquare) {\r
                        char buf[MSG_SIZ];\r
                        n = boards[currentMove][fromY][1];\r
-                       sprintf(buf, "%d %s%s", n, PieceToName(currentPiece,0), n == 1 ? "" : "s");\r
+                       snprintf(buf, MSG_SIZ, "%d %s%s", n, PieceToName(currentPiece,0), n == 1 ? "" : "s");\r
                        SayString(buf, TRUE);\r
                }\r
        } else\r
@@ -340,7 +340,7 @@ KeyboardEvent(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
                if(currentPiece != EmptySquare) {\r
                        char buf[MSG_SIZ];\r
                        n = boards[currentMove][fromY][BOARD_WIDTH-2];\r
-                       sprintf(buf, "%d %s%s", n, PieceToName(currentPiece,0), n == 1 ? "" : "s");\r
+                       snprintf(buf, MSG)SIZ,"%d %s%s", n, PieceToName(currentPiece,0), n == 1 ? "" : "s");\r
                        SayString(buf, TRUE);\r
                }\r
        } else\r
@@ -350,8 +350,8 @@ KeyboardEvent(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
                ynum = SquareToNum(fromY);\r
                if(currentPiece != EmptySquare) {\r
 //                     SayString(piece[0] == 'W' ? "white" : "black", TRUE);\r
-                       sprintf(buf, "%s %s %s", xchar, ynum, piece);\r
-               } else sprintf(buf, "%s %s", xchar, ynum);\r
+                 snprintf(buf, MSG_SIZ, "%s %s %s", xchar, ynum, piece);\r
+               } else snprintf(buf, MSG_SIZ, "%s %s", xchar, ynum);\r
                SayString(buf, TRUE);\r
        }\r
        return;\r
@@ -481,15 +481,15 @@ PossibleAttacked()
 VOID\r
 ReadRow()\r
 {\r
-       ChessSquare currentpiece; \r
+       ChessSquare currentpiece;\r
        char *piece, *xchar, *ynum ;\r
        int xPos, count=0;\r
        ynum = SquareToNum(fromY);\r
-       \r
+\r
        if(fromY < 0) return;\r
 \r
        for (xPos=BOARD_LEFT; xPos<BOARD_RGHT; xPos++) {\r
-               currentpiece = boards[currentMove][fromY][xPos];        \r
+               currentpiece = boards[currentMove][fromY][xPos];\r
                if(currentpiece != EmptySquare) {\r
                        piece = PieceToName(currentpiece,1);\r
                        xchar = SquareToChar(xPos);\r
@@ -509,15 +509,15 @@ ReadRow()
 VOID\r
 ReadColumn()\r
 {\r
-       ChessSquare currentpiece; \r
+       ChessSquare currentpiece;\r
        char *piece, *xchar, *ynum ;\r
        int yPos, count=0;\r
        xchar = SquareToChar(fromX);\r
-       \r
+\r
        if(fromX < 0) return;\r
 \r
        for (yPos=0; yPos<BOARD_HEIGHT; yPos++) {\r
-               currentpiece = boards[currentMove][yPos][fromX];        \r
+               currentpiece = boards[currentMove][yPos][fromX];\r
                if(currentpiece != EmptySquare) {\r
                        piece = PieceToName(currentpiece,1);\r
                        ynum = SquareToNum(yPos);\r
@@ -536,10 +536,10 @@ ReadColumn()
 VOID\r
 SayUpperDiagnols()\r
 {\r
-       ChessSquare currentpiece; \r
+       ChessSquare currentpiece;\r
        char *piece, *xchar, *ynum ;\r
        int yPos, xPos;\r
-       \r
+\r
        if(fromX < 0 || fromY < 0) return;\r
 \r
        if(fromX < BOARD_RGHT-1 && fromY < BOARD_HEIGHT-1) {\r
@@ -547,7 +547,7 @@ SayUpperDiagnols()
                yPos = fromY+1;\r
                xPos = fromX+1;\r
                while(yPos<BOARD_HEIGHT && xPos<BOARD_RGHT) {\r
-                       currentpiece = boards[currentMove][yPos][xPos]; \r
+                       currentpiece = boards[currentMove][yPos][xPos];\r
                        piece = PieceToName(currentpiece,1);\r
                        xchar = SquareToChar(xPos);\r
                        ynum = SquareToNum(yPos);\r
@@ -565,7 +565,7 @@ SayUpperDiagnols()
                yPos = fromY+1;\r
                xPos = fromX-1;\r
                while(yPos<BOARD_HEIGHT && xPos>=BOARD_LEFT) {\r
-                       currentpiece = boards[currentMove][yPos][xPos]; \r
+                       currentpiece = boards[currentMove][yPos][xPos];\r
                        piece = PieceToName(currentpiece,1);\r
                        xchar = SquareToChar(xPos);\r
                        ynum = SquareToNum(yPos);\r
@@ -582,10 +582,10 @@ SayUpperDiagnols()
 VOID\r
 SayLowerDiagnols()\r
 {\r
-       ChessSquare currentpiece; \r
+       ChessSquare currentpiece;\r
        char *piece, *xchar, *ynum ;\r
        int yPos, xPos;\r
-       \r
+\r
        if(fromX < 0 || fromY < 0) return;\r
 \r
        if(fromX < BOARD_RGHT-1 && fromY > 0) {\r
@@ -593,7 +593,7 @@ SayLowerDiagnols()
                yPos = fromY-1;\r
                xPos = fromX+1;\r
                while(yPos>=0 && xPos<BOARD_RGHT) {\r
-                       currentpiece = boards[currentMove][yPos][xPos]; \r
+                       currentpiece = boards[currentMove][yPos][xPos];\r
                        piece = PieceToName(currentpiece,1);\r
                        xchar = SquareToChar(xPos);\r
                        ynum = SquareToNum(yPos);\r
@@ -611,7 +611,7 @@ SayLowerDiagnols()
                yPos = fromY-1;\r
                xPos = fromX-1;\r
                while(yPos>=0 && xPos>=BOARD_LEFT) {\r
-                       currentpiece = boards[currentMove][yPos][xPos]; \r
+                       currentpiece = boards[currentMove][yPos][xPos];\r
                        piece = PieceToName(currentpiece,1);\r
                        xchar = SquareToChar(xPos);\r
                        ynum = SquareToNum(yPos);\r
@@ -628,11 +628,11 @@ SayLowerDiagnols()
 VOID\r
 SayKnightMoves()\r
 {\r
-       ChessSquare currentpiece, oldpiece; \r
+       ChessSquare currentpiece, oldpiece;\r
        char *piece, *xchar, *ynum ;\r
 \r
        oldpiece = boards[currentMove][fromY][fromX];\r
-       if(oldpiece == WhiteKnight || oldpiece == BlackKnight) \r
+       if(oldpiece == WhiteKnight || oldpiece == BlackKnight)\r
                SayString("The possible squares a Knight could move to are", FALSE);\r
        else\r
                SayString("The squares a Knight could possibly attack from are", FALSE);\r
@@ -666,7 +666,7 @@ SayKnightMoves()
                        SayString(piece, FALSE);\r
                }\r
        }\r
-       \r
+\r
        if (fromY+1 < BOARD_HEIGHT && fromX+2 < BOARD_RGHT) {\r
                currentpiece = boards[currentMove][fromY+1][fromX+2];\r
                if(((oldpiece == WhiteKnight) && (currentpiece > WhiteKing))\r
@@ -681,7 +681,7 @@ SayKnightMoves()
                        SayString(piece, FALSE);\r
                }\r
        }\r
-       \r
+\r
        if (fromY-1 >= 0 && fromX+2 < BOARD_RGHT) {\r
                currentpiece = boards[currentMove][fromY-1][fromX+2];\r
                if(((oldpiece == WhiteKnight) && (currentpiece > WhiteKing))\r
@@ -696,7 +696,7 @@ SayKnightMoves()
                        SayString(piece, FALSE);\r
                }\r
        }\r
-       \r
+\r
        if (fromY-2 >= 0 && fromX+1 < BOARD_RGHT) {\r
                currentpiece = boards[currentMove][fromY-2][fromX+1];\r
                if(((oldpiece == WhiteKnight) && (currentpiece > WhiteKing))\r
@@ -711,7 +711,7 @@ SayKnightMoves()
                        SayString(piece, FALSE);\r
                }\r
        }\r
-       \r
+\r
        if (fromY-2 >= 0 && fromX-1 >= BOARD_LEFT) {\r
                currentpiece = boards[currentMove][fromY-2][fromX-1];\r
                if(((oldpiece == WhiteKnight) && (currentpiece > WhiteKing))\r
@@ -726,7 +726,7 @@ SayKnightMoves()
                        SayString(piece, FALSE);\r
                }\r
        }\r
-       \r
+\r
        if (fromY-1 >= 0 && fromX-2 >= BOARD_LEFT) {\r
                currentpiece = boards[currentMove][fromY-1][fromX-2];\r
                if(((oldpiece == WhiteKnight) && (currentpiece > WhiteKing))\r
@@ -741,7 +741,7 @@ SayKnightMoves()
                        SayString(piece, FALSE);\r
                }\r
        }\r
-       \r
+\r
        if (fromY+1 < BOARD_HEIGHT && fromX-2 >= BOARD_LEFT) {\r
                currentpiece = boards[currentMove][fromY+1][fromX-2];\r
                if(((oldpiece == WhiteKnight) && (currentpiece > WhiteKing))\r
@@ -761,7 +761,7 @@ SayKnightMoves()
 VOID\r
 SayPieces(ChessSquare p)\r
 {\r
-       ChessSquare currentpiece;  \r
+       ChessSquare currentpiece;\r
        char *piece, *xchar, *ynum ;\r
        int yPos, xPos, count = 0;\r
        char buf[50];\r
@@ -769,13 +769,13 @@ SayPieces(ChessSquare p)
        if(p == WhitePlay)   SayString("White pieces", FALSE); else\r
        if(p == BlackPlay)   SayString("Black pieces", FALSE); else\r
        if(p == EmptySquare) SayString("Pieces", FALSE); else {\r
-               sprintf(buf, "%ss", PieceToName(p,1));\r
+         snprintf(buf, sizeof(buf)/sizeof(buf[0]),"%ss", PieceToName(p,1));\r
                SayString(buf, FALSE);\r
        }\r
        SayString("are located", FALSE);\r
        for(yPos=0; yPos<BOARD_HEIGHT; yPos++) {\r
                for(xPos=BOARD_LEFT; xPos<BOARD_RGHT; xPos++) {\r
-                       currentpiece = boards[currentMove][yPos][xPos]; \r
+                       currentpiece = boards[currentMove][yPos][xPos];\r
                        if(p == BlackPlay && currentpiece >= BlackPawn && currentpiece <= BlackKing ||\r
                           p == WhitePlay && currentpiece >= WhitePawn && currentpiece <= WhiteKing   )\r
                                piece = PieceToName(currentpiece,0);\r
@@ -784,7 +784,7 @@ SayPieces(ChessSquare p)
                        else if(p == currentpiece)\r
                                piece = NULL;\r
                        else continue;\r
-                               \r
+\r
                                if(count == 0) SayString("at", FALSE);\r
                                xchar = SquareToChar(xPos);\r
                                ynum = SquareToNum(yPos);\r
@@ -804,7 +804,7 @@ SayCurrentPos()
        char *piece, *xchar, *ynum ;\r
        if(fromX <  BOARD_LEFT) { SayString("You strayed into the white holdings", FALSE); return; }\r
        if(fromX >= BOARD_RGHT) { SayString("You strayed into the black holdings", FALSE); return; }\r
-       currentpiece = boards[currentMove][fromY][fromX];       \r
+       currentpiece = boards[currentMove][fromY][fromX];\r
        piece = PieceToName(currentpiece,1);\r
        ynum = SquareToNum(fromY);\r
        xchar = SquareToChar(fromX);\r
@@ -814,7 +814,7 @@ SayCurrentPos()
        SayString(piece, FALSE);\r
        if(((fromX-BOARD_LEFT) ^ fromY)&1)\r
                SayString("on a light square",FALSE);\r
-       else \r
+       else\r
                SayString("on a dark square",FALSE);\r
 \r
        PossibleAttacked();\r
@@ -827,28 +827,32 @@ SayAllBoard()
        int Xpos, Ypos;\r
        ChessSquare currentpiece;\r
        char *piece, *ynum ;\r
-       \r
+\r
        if(gameInfo.holdingsWidth) {\r
                int first = 0;\r
                for(Ypos=0; Ypos<gameInfo.holdingsSize; Ypos++) {\r
                        int n = boards[currentMove][Ypos][BOARD_WIDTH-2];\r
-                       if(n) {  char buf[MSG_SIZ];\r
-                               if(!first++) SayString("white holds", FALSE);\r
-                               currentpiece = boards[currentMove][Ypos][BOARD_WIDTH-1];        \r
-                               piece = PieceToName(currentpiece,0);\r
-                               sprintf(buf, "%d %s%s", n, piece, (n==1 ? "" : "s") );\r
-                               SayString(buf, FALSE);\r
+                       if(n) {\r
+                         char buf[MSG_SIZ];\r
+                         if(!first++)\r
+                           SayString("white holds", FALSE);\r
+                         currentpiece = boards[currentMove][Ypos][BOARD_WIDTH-1];\r
+                         piece = PieceToName(currentpiece,0);\r
+                         snprintf(buf, MSG_SIZ,"%d %s%s", n, piece, (n==1 ? "" : "s") );\r
+                         SayString(buf, FALSE);\r
                        }\r
                }\r
                first = 0;\r
                for(Ypos=BOARD_HEIGHT-1; Ypos>=BOARD_HEIGHT - gameInfo.holdingsSize; Ypos--) {\r
                        int n = boards[currentMove][Ypos][1];\r
-                       if(n) {  char buf[MSG_SIZ];\r
-                               if(!first++) SayString("black holds", FALSE);\r
-                               currentpiece = boards[currentMove][Ypos][0];    \r
-                               piece = PieceToName(currentpiece,0);\r
-                               sprintf(buf, "%d %s%s", n, piece, (n==1 ? "" : "s") );\r
-                               SayString(buf, FALSE);\r
+                       if(n) {\r
+                         char buf[MSG_SIZ];\r
+                         if(!first++)\r
+                           SayString("black holds", FALSE);\r
+                         currentpiece = boards[currentMove][Ypos][0];\r
+                         piece = PieceToName(currentpiece,0);\r
+                         snprintf(buf, MSG_SIZ, "%d %s%s", n, piece, (n==1 ? "" : "s") );\r
+                         SayString(buf, FALSE);\r
                        }\r
                }\r
        }\r
@@ -858,16 +862,17 @@ SayAllBoard()
                SayString(ynum, FALSE);\r
                SayString("rank", FALSE);\r
                for(Xpos=BOARD_LEFT; Xpos<BOARD_RGHT; Xpos++) {\r
-                       currentpiece = boards[currentMove][Ypos][Xpos]; \r
+                       currentpiece = boards[currentMove][Ypos][Xpos];\r
                        if(currentpiece != EmptySquare) {\r
                                int count = 0;\r
                                char buf[50];\r
                                piece = PieceToName(currentpiece,1);\r
                                while(Xpos < BOARD_RGHT && boards[currentMove][Ypos][Xpos] == currentpiece)\r
                                        Xpos++, count++;\r
-                               if(count > 1) { \r
-                                       sprintf(buf, "%d %ss", count, piece);\r
-                               } else  sprintf(buf, "%s", piece);\r
+                               if(count > 1)\r
+                                 snprintf(buf, sizeof(buf)/sizeof(buf[0]), "%d %ss", count, piece);\r
+                               else\r
+                                 snprintf(buf, sizeof(buf)/sizeof(buf[0]), "%s", piece);\r
                                Xpos--;\r
                                SayString(buf, FALSE);\r
                        } else {\r
@@ -877,9 +882,9 @@ SayAllBoard()
                                if(Xpos == BOARD_RGHT && oldX == BOARD_LEFT)\r
                                        SayString("all", FALSE);\r
                                else{\r
-                                   if(count > 1) { \r
+                                   if(count > 1) {\r
                                        char buf[10];\r
-                                       sprintf(buf, "%d", count);\r
+                                       snprintf(buf, sizeof(buf)/sizeof(buf[0]),"%d", count);\r
                                        SayString(buf, FALSE);\r
                                    }\r
                                    Xpos--;\r
@@ -888,7 +893,7 @@ SayAllBoard()
                        }\r
                }\r
        }\r
-       \r
+\r
 }\r
 \r
 VOID\r
@@ -903,12 +908,12 @@ SayWhosTurn()
                        SayString("It is your opponents turn", FALSE);\r
                else    SayString("It is your turn", FALSE);\r
        } else {\r
-               if(WhiteOnMove(currentMove)) \r
+               if(WhiteOnMove(currentMove))\r
                        SayString("White is on move here", FALSE);\r
                else    SayString("Black is on move here", FALSE);\r
        }\r
 }\r
-       \r
+\r
 extern char *commentList[];\r
 \r
 VOID\r
@@ -947,7 +952,7 @@ SayMachineMove(int evenIfDuplicate)
                                    c = 'W'; break;\r
                                  case IcsPlayingBlack:\r
                                  case MachinePlaysBlack:\r
-                                   c = 'B'; \r
+                                   c = 'B';\r
                                  default:\r
                                    break;\r
                                }\r
@@ -955,7 +960,7 @@ SayMachineMove(int evenIfDuplicate)
                            if(c != lastMover && !evenIfDuplicate) return; // line is thinking output of future move, ignore.\r
                            if(2*moveNr - (dotCount < 2) == previousMove)\r
                                return; // do not repeat same move; likely ponder output\r
-                           sprintf(buf, "score %s %d at %d ply", \r
+                           snprintf(buf, MSG_SIZ, "score %s %d at %d ply",\r
                                        score > 0 ? "plus" : score < 0 ? "minus" : "",\r
                                        (int) (fabs(score)*100+0.5),\r
                                        depth );\r
@@ -981,16 +986,16 @@ SayMachineMove(int evenIfDuplicate)
 \r
                n = 2*moveNr - (dotCount < 2);\r
 \r
-               if(previousMove != 2*moveNr + (dotCount > 1) || evenIfDuplicate) { \r
+               if(previousMove != 2*moveNr + (dotCount > 1) || evenIfDuplicate) {\r
                    char number[20];\r
                    previousMove = 2*moveNr + (dotCount > 1); // remember move nr of move last spoken\r
-                   sprintf(number, "%d", moveNr);\r
+                   snprintf(number, sizeof(number)/sizeof(number[0]),"%d", moveNr);\r
 \r
                    yPos = CoordToNum(messageText[len-1]);  /* turn char coords to ints */\r
                    xPos = CoordToNum(messageText[len-2]);\r
                    if(xPos < 0 || xPos > 11) return; // prevent crashes if no coord string available to speak\r
                    if(yPos < 0 || yPos > 9)  return;\r
-                   currentpiece = boards[n][yPos][xPos];       \r
+                   currentpiece = boards[n][yPos][xPos];\r
                    piece = PieceToName(currentpiece,0);\r
                    ynum = SquareToNum(yPos);\r
                    xchar = SquareToChar(xPos);\r
@@ -1044,8 +1049,8 @@ SayMachineMove(int evenIfDuplicate)
                if(StrStr(messageText, " 1/2-1/2")) p = "game ends in a draw";\r
                if(comment[0]) {\r
                    if(p) {\r
-                       if(!StrCaseStr(comment, "draw") && \r
-                          !StrCaseStr(comment, "white") && \r
+                       if(!StrCaseStr(comment, "draw") &&\r
+                          !StrCaseStr(comment, "white") &&\r
                           !StrCaseStr(comment, "black") ) {\r
                                SayString(p, FALSE);\r
                                SayString("due to", FALSE);\r
@@ -1074,11 +1079,11 @@ SayClockTime()
        suppressClocks = 1; // if user is using alt+T command, no reason to display them\r
        if(abs(lastWhiteTime - whiteTimeRemaining) < 1000 && abs(lastBlackTime - blackTimeRemaining) < 1000)\r
                suppressClocks = 0; // back on after two requests in rapid succession\r
-       sprintf(buf1, "%s", TimeString(whiteTimeRemaining));\r
+       snprintf(buf1, sizeof(buf1)/sizeof(buf1[0]),"%s", TimeString(whiteTimeRemaining));\r
        str1 = buf1;\r
        SayString("White clock", FALSE);\r
        SayString(str1, FALSE);\r
-       sprintf(buf2, "%s", TimeString(blackTimeRemaining));\r
+       snprintf(buf2, sizeof(buf2)/sizeof(buf2[0]), "%s", TimeString(blackTimeRemaining));\r
        str2 = buf2;\r
        SayString("Black clock", FALSE);\r
        SayString(str2, FALSE);\r
@@ -1101,7 +1106,7 @@ KeyboardMove(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
 {\r
        ChessSquare currentpiece;\r
        char *piece;\r
-       \r
+\r
        static BOOLEAN sameAgain = FALSE;\r
        switch (message) {\r
        case WM_KEYDOWN:\r
@@ -1112,20 +1117,20 @@ KeyboardMove(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
                        break;\r
                }\r
                else if(oldFromX != -1) {\r
-                       \r
+\r
                        ChessSquare pdown, pup;\r
       pdown = boards[currentMove][oldFromY][oldFromX];\r
       pup = boards[currentMove][fromY][fromX];\r
-               \r
+\r
                if (gameMode == EditPosition ||\r
                        !((WhitePawn <= pdown && pdown <= WhiteKing &&\r
                                 WhitePawn <= pup && pup <= WhiteKing) ||\r
                                (BlackPawn <= pdown && pdown <= BlackKing &&\r
                                 BlackPawn <= pup && pup <= BlackKing))) {\r
                        /* EditPosition, empty square, or different color piece;\r
-                       click-click move is possible */         \r
+                       click-click move is possible */\r
                        char promoChoice = NULLCHAR;\r
-               \r
+\r
                        if (HasPromotionChoice(oldFromX, oldFromY, fromX, fromY, &promoChoice)) {\r
                                if (appData.alwaysPromoteToQueen) {\r
                                        UserMoveEvent(oldFromX, oldFromY, fromX, fromY, 'q');\r
@@ -1134,7 +1139,7 @@ KeyboardMove(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
                                        toX = fromX; toY = fromY; fromX = oldFromX; fromY = oldFromY;\r
                                        PromotionPopup(hwnd);\r
                                        fromX = toX; fromY = toY;\r
-                               }       \r
+                               }\r
                        }\r
                        else {\r
                                UserMoveEvent(oldFromX, oldFromY, fromX, fromY, promoChoice);\r
@@ -1142,13 +1147,13 @@ KeyboardMove(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
                oldFromX = oldFromY = -1;\r
                break;\r
                }\r
-               \r
+\r
                }\r
                /* First downclick, or restart on a square with same color piece */\r
                if (OKToStartUserMove(fromX, fromY)) {\r
                oldFromX = fromX;\r
                oldFromY = fromY;\r
-               currentpiece = boards[currentMove][fromY][fromX];       \r
+               currentpiece = boards[currentMove][fromY][fromX];\r
                piece = PieceToName(currentpiece,1);\r
                SayString(piece, FALSE);\r
                SayString("selected", FALSE);\r
@@ -1164,7 +1169,7 @@ KeyboardMove(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
       if (sameAgain) {\r
        /* Clicked same square twice: abort click-click move */\r
                        oldFromX = oldFromY = -1;\r
-                       currentpiece = boards[currentMove][fromY][fromX];       \r
+                       currentpiece = boards[currentMove][fromY][fromX];\r
                        piece = PieceToName(currentpiece,0);\r
                        SayString(piece, FALSE);\r
                        SayString("unselected", FALSE);\r
index 1f78605..1da04b7 100644 (file)
@@ -3,7 +3,7 @@
  *\r
  * Author: H.G.Muller (August 2009)\r
  *\r
- * Copyright 2009, 2010 Free Software Foundation, Inc. \r
+ * Copyright 2009, 2010 Free Software Foundation, Inc.\r
  *\r
  * ------------------------------------------------------------------------\r
  *\r
@@ -193,7 +193,7 @@ LRESULT CALLBACK ChatProc( HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam
        if(partner<0) {\r
                for(i=0; i<MAX_CHAT; i++) if(chatHandle[i] == NULL) { partner = i; break; }\r
                chatHandle[partner] = hDlg;\r
-               sprintf(buf, "Chat Window %s", first.tidy);\r
+               snprintf(buf, MSG_SIZ, "Chat Window %s", first.tidy);\r
                SetWindowText(hDlg, buf);\r
         }\r
        for(i=0; i<MAX_CHAT; i++) if(chatHandle[i]) {\r
@@ -241,7 +241,7 @@ LRESULT CALLBACK ChatProc( HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam
     break;\r
 \r
     case WM_COMMAND:\r
-      /* \r
+      /*\r
         [AS]\r
         If <Enter> is pressed while editing the filter, it's better to apply\r
         the filter rather than selecting the current game.\r
@@ -287,16 +287,16 @@ LRESULT CALLBACK ChatProc( HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam
            // from here on it could be back-end\r
            SaveInHistory(mess);\r
            if(!strcmp("whispers", chatPartner[partner]))\r
-               sprintf(buf, "whisper %s\n", mess); // WHISPER box uses "whisper" to send\r
+             snprintf(buf, MSG_SIZ, "whisper %s\n", mess); // WHISPER box uses "whisper" to send\r
            else if(!strcmp("shouts", chatPartner[partner]))\r
-               sprintf(buf, "shout %s\n", mess); // SHOUT box uses "shout" to send\r
+             snprintf(buf, MSG_SIZ, "shout %s\n", mess); // SHOUT box uses "shout" to send\r
            else {\r
                if(!atoi(chatPartner[partner])) {\r
-                   sprintf(buf, "> %s\r\n", mess); // echo only tells to handle, not channel\r
+                 snprintf(buf, MSG_SIZ, "> %s\r\n", mess); // echo only tells to handle, not channel\r
                InsertIntoMemo(hDlg, buf);\r
-               sprintf(buf, "xtell %s %s\n", chatPartner[partner], mess);\r
+               snprintf(buf, MSG_SIZ, "xtell %s %s\n", chatPartner[partner], mess);\r
                } else\r
-               sprintf(buf, "tell %s %s\n", chatPartner[partner], mess);\r
+                 snprintf(buf, MSG_SIZ, "tell %s %s\n", chatPartner[partner], mess);\r
            }\r
            SendToICS(buf);\r
            break;\r
@@ -360,12 +360,12 @@ void ChatPopUp(char *icsHandle)
 {\r
   FARPROC lpProc;\r
   int i, partner = -1;\r
-  \r
+\r
   CheckMenuItem(GetMenu(hwndMain), IDM_NewChat, MF_CHECKED);\r
   for(i=0; i<MAX_CHAT; i++) if(chatHandle[i] == NULL) { partner = i; break; }\r
   if(partner == -1) { DisplayError("You first have to close a Chat Box\nbefore you can open a new one", 0); return; }\r
   if(icsHandle) // [HGM] clickbox set handle in advance\r
-    safeStrCpy(chatPartner[partner], icsHandle, \r
+    safeStrCpy(chatPartner[partner], icsHandle,\r
               sizeof(chatPartner[partner])/sizeof(chatPartner[partner][0]) );\r
   else chatPartner[partner][0] = NULLCHAR;\r
   chatCount++;\r
index e582a46..e13bcf0 100644 (file)
@@ -66,7 +66,7 @@ static int GameListToListBox( HWND hDlg, BOOL boReset, char * pszFilter, struct
     struct GameListStats dummy;\r
 \r
     /* Initialize stats (use a dummy variable if caller not interested in them) */\r
-    if( stats == NULL ) { \r
+    if( stats == NULL ) {\r
         stats = &dummy;\r
     }\r
 \r
@@ -124,7 +124,7 @@ static int GameListUpdateTitle( HWND hDlg, char * pszTitle, int item_count, int
 {\r
     char buf[256];\r
 \r
-    sprintf( buf, _("%s - %d/%d games"), pszTitle, item_count, item_total );\r
+    snprintf( buf, sizeof(buf)/sizeof(buf[0]),_("%s - %d/%d games"), pszTitle, item_count, item_total );\r
 \r
     if( stats != 0 ) {\r
         sprintf( buf+strlen(buf), " (%d-%d-%d)", stats->white_wins, stats->black_wins, stats->drawn );\r
@@ -153,7 +153,7 @@ GameListDialog(HWND hDlg, UINT message,     WPARAM wParam, LPARAM lParam)
   static SnapData sd;\r
 \r
   switch (message) {\r
-  case WM_INITDIALOG: \r
+  case WM_INITDIALOG:\r
     Translate(hDlg, DLG_GameList);\r
     GetWindowText( hDlg, szDlgTitle, sizeof(szDlgTitle) );\r
     szDlgTitle[ sizeof(szDlgTitle)-1 ] = '\0';\r
@@ -203,13 +203,13 @@ GameListDialog(HWND hDlg, UINT message,   WPARAM wParam, LPARAM lParam)
                              newSizeX, newSizeY);\r
        sizeX = newSizeX;\r
        sizeY = newSizeY;\r
-      } else \r
+      } else\r
         GetActualPlacement( gameListDialog, &wpGameList );\r
 \r
     }\r
       GameListUpdateTitle( hDlg, _("Game List"), count, ((ListGame *) gameList.tailPred)->number, &stats ); // [HGM] always update title\r
     return FALSE;\r
-    \r
+\r
   case WM_SIZE:\r
     newSizeX = LOWORD(lParam);\r
     newSizeY = HIWORD(lParam);\r
@@ -230,7 +230,7 @@ GameListDialog(HWND hDlg, UINT message,     WPARAM wParam, LPARAM lParam)
 \r
   case WM_EXITSIZEMOVE:\r
     return OnExitSizeMove( &sd, hDlg, wParam, lParam );\r
-  \r
+\r
   case WM_GETMINMAXINFO:\r
     /* Prevent resizing window too small */\r
     mmi = (MINMAXINFO *) lParam;\r
@@ -239,7 +239,7 @@ GameListDialog(HWND hDlg, UINT message,     WPARAM wParam, LPARAM lParam)
     break;\r
 \r
   case WM_COMMAND:\r
-      /* \r
+      /*\r
         [AS]\r
         If <Enter> is pressed while editing the filter, it's better to apply\r
         the filter rather than selecting the current game.\r
@@ -270,7 +270,7 @@ GameListDialog(HWND hDlg, UINT message,     WPARAM wParam, LPARAM lParam)
        return TRUE;\r
       }\r
       break; /* load the game*/\r
-      \r
+\r
     case OPT_GameListNext:\r
       nItem = SendDlgItemMessage(hDlg, OPT_GameListText, LB_GETCURSEL, 0, 0);\r
       nItem++;\r
@@ -281,7 +281,7 @@ GameListDialog(HWND hDlg, UINT message,     WPARAM wParam, LPARAM lParam)
       }\r
       SendDlgItemMessage(hDlg, OPT_GameListText, LB_SETCURSEL, nItem, 0);\r
       break; /* load the game*/\r
-      \r
+\r
     case OPT_GameListPrev:\r
       nItem = SendDlgItemMessage(hDlg, OPT_GameListText, LB_GETCURSEL, 0, 0);\r
       nItem--;\r
@@ -297,7 +297,7 @@ GameListDialog(HWND hDlg, UINT message,     WPARAM wParam, LPARAM lParam)
     case IDC_GameListDoFilter:\r
         {\r
             char filter[MAX_FILTER_LENGTH+1];\r
-            \r
+\r
             if( GetDlgItemText( hDlg, IDC_GameListFilter, filter, sizeof(filter) ) >= 0 ) {\r
                 filter[ sizeof(filter)-1 ] = '\0';\r
                 count = GameListToListBox( hDlg, TRUE, filter, &stats );\r
@@ -311,13 +311,13 @@ GameListDialog(HWND hDlg, UINT message,   WPARAM wParam, LPARAM lParam)
     case OPT_GameListClose:\r
       GameListPopDown();\r
       return TRUE;\r
-      \r
+\r
     case OPT_GameListText:\r
       switch (HIWORD(wParam)) {\r
       case LBN_DBLCLK:\r
        nItem = SendMessage((HWND) lParam, LB_GETCURSEL, 0, 0);\r
        break; /* load the game*/\r
-       \r
+\r
       default:\r
        return FALSE;\r
       }\r
@@ -376,7 +376,7 @@ GameListDialog(HWND hDlg, UINT message,     WPARAM wParam, LPARAM lParam)
 VOID GameListPopUp(FILE *fp, char *filename)\r
 {\r
   FARPROC lpProc;\r
-  \r
+\r
   gameFile = fp;\r
   if (gameFileName != filename) {\r
     if (gameFileName) free(gameFileName);\r
@@ -407,7 +407,7 @@ VOID GameListPopDown(void)
 VOID GameListHighlight(int index)\r
 {\r
   if (gameListDialog == NULL) return;\r
-  SendDlgItemMessage(gameListDialog, OPT_GameListText, \r
+  SendDlgItemMessage(gameListDialog, OPT_GameListText,\r
     LB_SETCURSEL, index - 1, 0);\r
 }\r
 \r
index 6f5e32e..b535d44 100644 (file)
@@ -344,7 +344,7 @@ LoadLanguageFile(char *name)
     char buf[MSG_SIZ];\r
 \r
     if(!name || name[0] == NULLCHAR) return;\r
-    sprintf(buf, "%s%s", name, strchr(name, '.') ? "" : ".lng"); // auto-append lng extension\r
+      snprintf(buf, MSG_SIZ, "%s%s", name, strchr(name, '.') ? "" : ".lng"); // auto-append lng extension\r
     if(!strcmp(buf, oldLanguage)) { barbaric = 1; return; } // this language already loaded; just switch on\r
     if((f = fopen(buf, "r")) == NULL) return;\r
     while((k = fgetc(f)) != EOF) {\r
@@ -430,7 +430,7 @@ TranslateMenus(int addLanguage)
           for(j=GetMenuItemCount(subMenu)-1; j>=0; j--){\r
             char buf[MSG_SIZ];\r
             UINT k = GetMenuItemID(subMenu, j);\r
-             if(menuText[i][j]) 
+             if(menuText[i][j])
                safeStrCpy(buf, menuText[i][j], sizeof(buf)/sizeof(buf[0]) ); else {\r
                 GetMenuString(subMenu, j, buf, MSG_SIZ, MF_BYPOSITION);\r
                 menuText[i][j] = strdup(buf); // remember original on first change\r
@@ -881,7 +881,7 @@ SetUserLogo()
     if(appData.autoLogo) {\r
          curName = UserName();\r
          if(strcmp(curName, oldUserName)) {\r
-               sprintf(oldUserName, "logos\\%s.bmp", curName);\r
+           snprintf(oldUserName, MSG_SIZ, "logos\\%s.bmp", curName);\r
                userLogo = LoadImage( 0, oldUserName, IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE );    \r
                safeStrCpy(oldUserName, curName, sizeof(oldUserName)/sizeof(oldUserName[0]) );\r
          }\r
@@ -1004,7 +1004,7 @@ InitInstance(HINSTANCE hInstance, int nCmdShow, LPSTR lpCmdLine)
   } else if(appData.autoLogo) {\r
       if(appData.firstDirectory && appData.firstDirectory[0]) {\r
        char buf[MSG_SIZ];\r
-       sprintf(buf, "%s/logo.bmp", appData.firstDirectory);\r
+         snprintf(buf, MSG_SIZ, "%s/logo.bmp", appData.firstDirectory);\r
        first.programLogo = LoadImage( 0, buf, IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE );   \r
       }\r
   }\r
@@ -1018,11 +1018,11 @@ InitInstance(HINSTANCE hInstance, int nCmdShow, LPSTR lpCmdLine)
   } else if(appData.autoLogo) {\r
       char buf[MSG_SIZ];\r
       if(appData.icsActive) { // [HGM] logo: in ICS mode second can be used for ICS\r
-       sprintf(buf, "logos\\%s.bmp", appData.icsHost);\r
+       snprintf(buf, MSG_SIZ, "logos\\%s.bmp", appData.icsHost);\r
        second.programLogo = LoadImage( 0, buf, IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE );\r
       } else\r
       if(appData.secondDirectory && appData.secondDirectory[0]) {\r
-       sprintf(buf, "%s\\logo.bmp", appData.secondDirectory);\r
+       snprintf(buf, MSG_SIZ, "%s\\logo.bmp", appData.secondDirectory);\r
        second.programLogo = LoadImage( 0, buf, IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE );  \r
       }\r
   }\r
@@ -1289,7 +1289,7 @@ ParseColorName(char *name)
       &red, &green, &blue);\r
   }\r
   if (count != 3) {\r
-    sprintf(buf, _("Can't parse color name %s"), name);\r
+    snprintf(buf, MSG_SIZ, _("Can't parse color name %s"), name);\r
     DisplayError(buf, 0);\r
     return RGB(0, 0, 0);\r
   }\r
@@ -2061,7 +2061,7 @@ DoLoadBitmap(HINSTANCE hinst, char *piece, int squareSize, char *suffix)
 {\r
   char name[128];\r
 \r
-  sprintf(name, "%s%d%s", piece, squareSize, suffix);\r
+    snprintf(name, sizeof(name)/sizeof(name[0]), "%s%d%s", piece, squareSize, suffix);\r
   if (gameInfo.event &&\r
       strcmp(gameInfo.event, "Easter Egg Hunt") == 0 &&\r
       strcmp(name, "k80s") == 0) {\r
@@ -2235,9 +2235,9 @@ InitDrawingSizes(BoardSize boardSize, int flags)
   /* Get text area sizes */\r
   hdc = GetDC(hwndMain);\r
   if (appData.clockMode) {\r
-    sprintf(buf, _("White: %s"), TimeString(23*60*60*1000L));\r
+    snprintf(buf, MSG_SIZ, _("White: %s"), TimeString(23*60*60*1000L));\r
   } else {\r
-    sprintf(buf, _("White"));\r
+    snprintf(buf, MSG_SIZ, _("White"));\r
   }\r
   oldFont = SelectObject(hdc, font[boardSize][CLOCK_FONT]->hf);\r
   GetTextExtentPoint(hdc, buf, strlen(buf), &clockSize);\r
@@ -4012,7 +4012,7 @@ SetupDropMenu(HMENU hmenu)
               dropEnables[i].piece);\r
     count = 0;\r
     while (p && *p++ == dropEnables[i].piece) count++;\r
-    sprintf(item, "%s  %d", T_(dropEnables[i].name), count);\r
+      snprintf(item, MSG_SIZ, "%s  %d", T_(dropEnables[i].name), count);\r
     enable = count > 0 || !appData.testLegality\r
       /*!!temp:*/ || (gameInfo.variant == VariantCrazyhouse\r
                      && !appData.icsActive);\r
@@ -4835,14 +4835,14 @@ WndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
 \r
     case IDM_AnalysisMode:\r
       if (!first.analysisSupport) {\r
-        sprintf(buf, _("%s does not support analysis"), first.tidy);\r
+        snprintf(buf, MSG_SIZ, _("%s does not support analysis"), first.tidy);\r
         DisplayError(buf, 0);\r
       } else {\r
        SAY("analyzing current position");\r
         /* [DM] icsEngineAnlyze [HGM] Why is this front-end??? */\r
         if (appData.icsActive) {\r
                if (gameMode != IcsObserving) {\r
-                       sprintf(buf, "You are not observing a game");\r
+                snprintf(buf, MSG_SIZ, "You are not observing a game");\r
                        DisplayError(buf, 0);\r
                        /* secure check */\r
                        if (appData.icsEngineAnalyze) {\r
@@ -4872,7 +4872,7 @@ WndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
     case IDM_AnalyzeFile:\r
       if (!first.analysisSupport) {\r
         char buf[MSG_SIZ];\r
-        sprintf(buf, _("%s does not support analysis"), first.tidy);\r
+         snprintf(buf, MSG_SIZ, _("%s does not support analysis"), first.tidy);\r
         DisplayError(buf, 0);\r
       } else {\r
        if (!appData.showThinking) ToggleShowThinking();\r
@@ -5595,7 +5595,7 @@ MyLoadSound(MySound *ms)
   }\r
   if (!ok) {\r
     char buf[MSG_SIZ];\r
-    sprintf(buf, _("Error loading sound %s"), ms->name);\r
+      snprintf(buf, MSG_SIZ, _("Error loading sound %s"), ms->name);\r
     DisplayError(buf, GetLastError());\r
   }\r
   return ok;\r
@@ -5990,10 +5990,10 @@ InitEngineBox(HWND hDlg, HWND hwndCombo, char* nthcp, char* nthd, char* nthdir,
 \r
   InitComboStringsFromOption(hwndCombo, nthnames);\r
   q = QuoteForFilename(nthcp);\r
-  sprintf(buf, "%s%s%s", q, nthcp, q);\r
+    snprintf(buf, MSG_SIZ, "%s%s%s", q, nthcp, q);\r
   if (*nthdir != NULLCHAR) {\r
     q = QuoteForFilename(nthdir);\r
-    sprintf(buf + strlen(buf), " /%s=%s%s%s", nthd, q, nthdir, q);\r
+      snprintf(buf + strlen(buf), MSG_SIZ, " /%s=%s%s%s", nthd, q, nthdir, q);\r
   }\r
   if (*nthcp == NULLCHAR) {\r
     SendMessage(hwndCombo, CB_SETCURSEL, (WPARAM) 0, (LPARAM) 0);\r
@@ -6024,7 +6024,7 @@ StartupDialog(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
                  secondChessProgramNames);\r
     hwndCombo = GetDlgItem(hDlg, OPT_ChessServerName);\r
     InitComboStringsFromOption(hwndCombo, icsNames);    \r
-    sprintf(buf, "%s /icsport=%s", appData.icsHost, appData.icsPort);\r
+      snprintf(buf, MSG_SIZ, "%s /icsport=%s", appData.icsHost, appData.icsPort);\r
     if (*appData.icsHelper != NULLCHAR) {\r
       char *q = QuoteForFilename(appData.icsHelper);\r
       sprintf(buf + strlen(buf), " /icshelper=%s%s%s", q, appData.icsHelper, q);\r
@@ -6464,7 +6464,7 @@ TypeInNameDialog(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
       SetUserLogo();\r
       SetGameInfo();\r
       if(gameMode == MachinePlaysWhite || gameMode == MachinePlaysBlack) {\r
-       sprintf(move, "%s vs. %s", gameInfo.white, gameInfo.black);\r
+       snprintf(move, MSG_SIZ, "%s vs. %s", gameInfo.white, gameInfo.black);\r
        DisplayTitle(move);\r
       }\r
 \r
@@ -6795,12 +6795,12 @@ CommandX(HWND hwnd, char *command, BOOLEAN getname, BOOLEAN immediate)
     SendMessage(hwnd, EM_GETSELTEXT, 0, (LPARAM) name);\r
   }\r
   if (immediate) {\r
-    sprintf(buf, "%s %s", command, name);\r
+    snprintf(buf, MSG_SIZ, "%s %s", command, name);\r
     SetWindowText(hInput, buf);\r
     SendMessage(hInput, WM_CHAR, '\r', 0);\r
   } else {\r
     if(!strcmp(command, "chat")) { ChatPopUp(name); return; }\r
-    sprintf(buf, "%s %s ", command, name); /* trailing space */\r
+      snprintf(buf, MSG_SIZ, "%s %s ", command, name); /* trailing space */\r
     SetWindowText(hInput, buf);\r
     sel.cpMin = 999999;\r
     sel.cpMax = 999999;\r
@@ -7366,7 +7366,8 @@ DisplayHoldingsCount(HDC hdc, int x, int y, int rightAlign, int copyNumber)
   HFONT oldFont;\r
   RECT rect;\r
 \r
-  if(copyNumber > 1) sprintf(buf, "%d", copyNumber); else buf[0] = 0;\r
+  if(copyNumber > 1)
+    snprintf(buf, sizeof(buf)/sizeof(buf[0]),"%d", copyNumber); else buf[0] = 0;\r
 \r
   oldFg = SetTextColor(hdc, RGB(255, 255, 255)); /* white */\r
   oldBg = SetBkColor(hdc, RGB(0, 0, 0)); /* black */\r
@@ -7399,9 +7400,9 @@ DisplayAClock(HDC hdc, int timeRemaining, int highlight,
 \r
   if (appData.clockMode) {\r
     if (tinyLayout)\r
-      sprintf(buf, "%c %s %s", color[0], TimeString(timeRemaining), flagFell);\r
+      snprintf(buf, sizeof(buf)/sizeof(buf[0]), "%c %s %s", color[0], TimeString(timeRemaining), flagFell);\r
     else\r
-      sprintf(buf, "%s:%c%s %s", color, (logoHeight>0 ? 0 : ' '), TimeString(timeRemaining), flagFell);\r
+      snprintf(buf, sizeof(buf)/sizeof(buf[0]), "%s:%c%s %s", color, (logoHeight>0 ? 0 : ' '), TimeString(timeRemaining), flagFell);\r
     str = buf;\r
   } else {\r
     str = color;\r
@@ -7423,7 +7424,7 @@ DisplayAClock(HDC hdc, int timeRemaining, int highlight,
             rect, str, strlen(str), NULL);\r
   if(logoHeight > 0 && appData.clockMode) {\r
       RECT r;\r
-      sprintf(buf, "%s %s", buf+7, flagFell);\r
+      snprintf(buf, sizeof(buf)/sizeof(buf[0]), "%s %s", buf+7, flagFell);\r
       r.top = rect->top + logoHeight/2;\r
       r.left = rect->left;\r
       r.right = rect->right;\r
@@ -8056,7 +8057,7 @@ DisplayTitle(char *str)
       host = "ICS";\r
     else \r
       host = appData.icsHost;\r
-    sprintf(title, "%s: %s", szTitle, host);\r
+      snprintf(title, MSG_SIZ, "%s: %s", szTitle, host);\r
   } else if (appData.noChessProgram) {\r
     safeStrCpy(title, szTitle, sizeof(title)/sizeof(title[0]) );\r
   } else {\r
@@ -8121,14 +8122,14 @@ DisplayError(char *str, int error)
                        NULL, error, LANG_NEUTRAL,\r
                        (LPSTR) buf2, MSG_SIZ, NULL);\r
     if (len > 0) {\r
-      sprintf(buf, "%s:\n%s", str, buf2);\r
+      snprintf(buf, 2*MSG_SIZ, "%s:\n%s", str, buf2);\r
     } else {\r
       ErrorMap *em = errmap;\r
       while (em->err != 0 && em->err != error) em++;\r
       if (em->err != 0) {\r
-       sprintf(buf, "%s:\n%s", str, em->msg);\r
+       snprintf(buf, 2*MSG_SIZ, "%s:\n%s", str, em->msg);\r
       } else {\r
-       sprintf(buf, "%s:\nError code %d", str, error);\r
+       snprintf(buf, 2*MSG_SIZ, "%s:\nError code %d", str, error);\r
       }\r
     }\r
   }\r
@@ -8163,14 +8164,14 @@ DisplayFatalError(char *str, int error, int exitStatus)
                        NULL, error, LANG_NEUTRAL,\r
                        (LPSTR) buf2, MSG_SIZ, NULL);\r
     if (len > 0) {\r
-      sprintf(buf, "%s:\n%s", str, buf2);\r
+      snprintf(buf, 2*MSG_SIZ, "%s:\n%s", str, buf2);\r
     } else {\r
       ErrorMap *em = errmap;\r
       while (em->err != 0 && em->err != error) em++;\r
       if (em->err != 0) {\r
-       sprintf(buf, "%s:\n%s", str, em->msg);\r
+       snprintf(buf, 2*MSG_SIZ, "%s:\n%s", str, em->msg);\r
       } else {\r
-       sprintf(buf, "%s:\nError code %d", str, error);\r
+       snprintf(buf, 2*MSG_SIZ, "%s:\nError code %d", str, error);\r
       }\r
     }\r
     str = buf;\r
@@ -8301,7 +8302,7 @@ LRESULT CALLBACK NewGameFRC_Proc(HWND hDlg, UINT message, WPARAM wParam, LPARAM
             }\r
             return TRUE;\r
         case IDC_NFG_Random:\r
-            sprintf( buf, "%d", myrandom() ); /* [HGM] shuffle: no longer limit to 960 */\r
+         snprintf( buf, sizeof(buf)/sizeof(buf[0]), "%d", myrandom() ); /* [HGM] shuffle: no longer limit to 960 */\r
             SetDlgItemText(hDlg, IDC_NFG_Edit, buf );\r
             return TRUE;\r
         }\r
@@ -8453,7 +8454,7 @@ DisplayIcsInteractionTitle(char *str)
 {\r
   char consoleTitle[MSG_SIZ];\r
 \r
-  sprintf(consoleTitle, "%s: %s", szConsoleTitle, str);\r
+    snprintf(consoleTitle, MSG_SIZ, "%s: %s", szConsoleTitle, str);\r
   SetWindowText(hwndConsole, consoleTitle);\r
 }\r
 \r
@@ -9019,9 +9020,9 @@ OpenTelnet(char *host, char *port, ProcRef *pr)
   char cmdLine[MSG_SIZ];\r
 \r
   if (port[0] == NULLCHAR) {\r
-    sprintf(cmdLine, "%s %s", appData.telnetProgram, host);\r
+    snprintf(cmdLine, MSG_SIZ, "%s %s", appData.telnetProgram, host);\r
   } else {\r
-    sprintf(cmdLine, "%s %s %s", appData.telnetProgram, host, port);\r
+    snprintf(cmdLine, MSG_SIZ, "%s %s %s", appData.telnetProgram, host, port);\r
   }\r
   return StartChildProcess(cmdLine, "", pr);\r
 }\r
@@ -9120,7 +9121,7 @@ OpenCommPort(char *name, ProcRef *pr)
   char fullname[MSG_SIZ];\r
 \r
   if (*name != '\\')\r
-    sprintf(fullname, "\\\\.\\%s", name);\r
+    snprintf(fullname, MSG_SIZ, "\\\\.\\%s", name);\r
   else\r
     safeStrCpy(fullname, name, sizeof(fullname)/sizeof(fullname[0]) );\r
 \r
@@ -9292,7 +9293,7 @@ OpenRcmd(char* host, char* user, char* cmd, ProcRef* pr)
     break;\r
   }\r
   prevStderrPort = fromPort; // remember port used\r
-  sprintf(stderrPortStr, "%d", fromPort);\r
+  snprintf(stderrPortStr, MSG_SIZ, "%d", fromPort);\r
 \r
   if (send(s, stderrPortStr, strlen(stderrPortStr) + 1, 0) == SOCKET_ERROR) {\r
     err = WSAGetLastError();\r
index 9460aa0..2913b68 100644 (file)
@@ -54,7 +54,7 @@ extern HINSTANCE hInst;          /* current instance */
 extern HWND hwndMain;            /* root window*/\r
 extern BOOLEAN alwaysOnTop;\r
 extern RECT boardRect;\r
-extern COLORREF lightSquareColor, darkSquareColor, whitePieceColor, \r
+extern COLORREF lightSquareColor, darkSquareColor, whitePieceColor,\r
   blackPieceColor, highlightSquareColor, premoveHighlightColor;\r
 extern HPALETTE hPal;\r
 extern BoardSize boardSize;\r
@@ -100,15 +100,15 @@ LRESULT CALLBACK SaveOptions(HWND, UINT, WPARAM, LPARAM);
 LRESULT CALLBACK TimeControl(HWND, UINT, WPARAM, LPARAM);\r
 VOID ChangeBoardSize(BoardSize newSize);\r
 VOID PaintSampleSquare(\r
-    HWND     hwnd, \r
-    int      ctrlid, \r
-    COLORREF squareColor, \r
+    HWND     hwnd,\r
+    int      ctrlid,\r
+    COLORREF squareColor,\r
     COLORREF pieceColor,\r
     COLORREF squareOutlineColor,\r
     COLORREF pieceDetailColor,\r
     BOOL     isWhitePiece,\r
     BOOL     isMono,\r
-    HBITMAP  pieces[3] \r
+    HBITMAP  pieces[3]\r
     );\r
 VOID PaintColorBlock(HWND hwnd, int ctrlid, COLORREF color);\r
 VOID SetBoardOptionEnables(HWND hDlg);\r
@@ -196,9 +196,9 @@ GeneralOptionsDialog(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
                 appData.icsActive || !appData.noChessProgram);\r
     EnableWindow(GetDlgItem(hDlg, OPT_PonderNextMove),\r
                 !appData.noChessProgram);\r
-    EnableWindow(GetDlgItem(hDlg, OPT_PeriodicUpdates), \r
+    EnableWindow(GetDlgItem(hDlg, OPT_PeriodicUpdates),\r
                 !appData.noChessProgram && !appData.icsActive);\r
-    EnableWindow(GetDlgItem(hDlg, OPT_ShowThinking), \r
+    EnableWindow(GetDlgItem(hDlg, OPT_ShowThinking),\r
                 !appData.noChessProgram);\r
     return TRUE;\r
 \r
@@ -207,7 +207,7 @@ GeneralOptionsDialog(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
     switch (LOWORD(wParam)) {\r
     case IDOK:\r
       /* Read changed options from the dialog box */\r
-      \r
+\r
 #define IS_CHECKED(x) (Boolean)IsDlgButtonChecked(hDlg, (x))\r
 \r
       alwaysOnTop                  = IS_CHECKED(OPT_AlwaysOnTop);\r
@@ -250,7 +250,7 @@ GeneralOptionsDialog(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
        ClearHighlights();\r
        DrawPosition(FALSE, NULL);\r
       }\r
-      /* \r
+      /*\r
        * for some reason the redraw seems smoother when we invalidate\r
        * the board rect after the call to EndDialog()\r
        */\r
@@ -261,7 +261,7 @@ GeneralOptionsDialog(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
        InitDrawingSizes(boardSize, 0);\r
       } else if (oldShowButtonBar != appData.showButtonBar) {\r
        InitDrawingSizes(boardSize, 0);\r
-      } else if ((oldShowCoords != appData.showCoords) || \r
+      } else if ((oldShowCoords != appData.showCoords) ||\r
                 (oldBlindfold != appData.blindfold)) {\r
        InvalidateRect(hwndMain, &boardRect, FALSE);\r
       }\r
@@ -278,7 +278,7 @@ GeneralOptionsDialog(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
   return FALSE;\r
 }\r
 \r
-VOID \r
+VOID\r
 GeneralOptionsPopup(HWND hwnd)\r
 {\r
   FARPROC lpProc;\r
@@ -307,15 +307,15 @@ ChangeBoardSize(BoardSize newSize)
 \r
 VOID\r
 PaintSampleSquare(\r
-    HWND     hwnd, \r
-    int      ctrlid, \r
-    COLORREF squareColor, \r
+    HWND     hwnd,\r
+    int      ctrlid,\r
+    COLORREF squareColor,\r
     COLORREF pieceColor,\r
     COLORREF squareOutlineColor,\r
     COLORREF pieceDetailColor,\r
     BOOL     isWhitePiece,\r
     BOOL     isMono,\r
-    HBITMAP  pieces[3] \r
+    HBITMAP  pieces[3]\r
     )\r
 {\r
   HBRUSH  brushSquare;\r
@@ -358,15 +358,15 @@ PaintSampleSquare(
   brushPiece          = CreateSolidBrush(pieceColor);\r
   brushPieceDetail    = CreateSolidBrush(pieceDetailColor);\r
 \r
-  /* \r
-   * first draw the rectangle \r
+  /*\r
+   * first draw the rectangle\r
    */\r
   pen      = CreatePen(PS_SOLID, BORDER, squareOutlineColor);\r
   oldPen   = (HPEN)  SelectObject(hdcMem, pen);\r
   oldBrushSquare = (HBRUSH)SelectObject(hdcMem, brushSquare);\r
   Rectangle(hdcMem, rect.left, rect.top, rect.right, rect.bottom);\r
 \r
-  /* \r
+  /*\r
    * now draw the piece\r
    */\r
   if (isMono) {\r
@@ -378,23 +378,23 @@ PaintSampleSquare(
     if (isWhitePiece) {\r
       oldBitmapTemp = SelectObject(hdcTemp, pieces[WHITE]);\r
       oldBrushPiece = SelectObject(hdcMem, brushPiece);\r
-      BitBlt(hdcMem, x, y, SAMPLE_SQ_SIZE, SAMPLE_SQ_SIZE, \r
+      BitBlt(hdcMem, x, y, SAMPLE_SQ_SIZE, SAMPLE_SQ_SIZE,\r
             hdcTemp, 0, 0, 0x00B8074A);\r
       /* Use black for outline of white pieces */\r
       SelectObject(hdcTemp, pieces[OUTLINE]);\r
-      BitBlt(hdcMem, x, y, SAMPLE_SQ_SIZE, SAMPLE_SQ_SIZE, \r
+      BitBlt(hdcMem, x, y, SAMPLE_SQ_SIZE, SAMPLE_SQ_SIZE,\r
             hdcTemp, 0, 0, SRCAND);\r
     } else {\r
       /* Use square color for details of black pieces */\r
       oldBitmapTemp = SelectObject(hdcTemp, pieces[SOLID]);\r
       oldBrushPiece = SelectObject(hdcMem, brushPiece);\r
-      BitBlt(hdcMem, x, y, SAMPLE_SQ_SIZE, SAMPLE_SQ_SIZE, \r
+      BitBlt(hdcMem, x, y, SAMPLE_SQ_SIZE, SAMPLE_SQ_SIZE,\r
             hdcTemp, 0, 0, 0x00B8074A);\r
     }\r
     SelectObject(hdcMem, oldBrushPiece);\r
     SelectObject(hdcTemp, oldBitmapTemp);\r
   }\r
-  /* \r
+  /*\r
    * copy the memory dc to the screen\r
    */\r
   SelectObject(hdcMem, bufferBitmap);\r
@@ -403,7 +403,7 @@ PaintSampleSquare(
         rect.bottom - rect.top,\r
         hdcMem, rect.left, rect.top, SRCCOPY);\r
   SelectObject(hdcMem, oldBitmapMem);\r
-  /* \r
+  /*\r
    * clean up\r
    */\r
   SelectObject(hdcMem, oldBrushPiece);\r
@@ -466,7 +466,7 @@ SetBoardOptionEnables(HWND hDlg)
   }\r
 }\r
 \r
-BoardSize \r
+BoardSize\r
 BoardOptionsWhichRadio(HWND hDlg)\r
 {\r
   return (IsDlgButtonChecked(hDlg, OPT_SizeTiny) ? SizeTiny :\r
@@ -572,7 +572,7 @@ BoardOptionsDialog(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
     pieces[0] = DoLoadBitmap(hInst, "n", SAMPLE_SQ_SIZE, "s");\r
     pieces[1] = DoLoadBitmap(hInst, "n", SAMPLE_SQ_SIZE, "w");\r
     pieces[2] = DoLoadBitmap(hInst, "n", SAMPLE_SQ_SIZE, "o");\r
-       \r
+\r
     lsc = lightSquareColor;\r
     dsc = darkSquareColor;\r
     wpc = whitePieceColor;\r
@@ -604,7 +604,7 @@ BoardOptionsDialog(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
   case WM_COMMAND: /* message: received a command */\r
     switch (LOWORD(wParam)) {\r
     case IDOK:\r
-      /* \r
+      /*\r
        * if we call EndDialog() after the call to ChangeBoardSize(),\r
        * then ChangeBoardSize() does not take effect, although the new\r
        * boardSize is saved. Go figure...\r
@@ -657,42 +657,42 @@ BoardOptionsDialog(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
       return TRUE;\r
 \r
     case OPT_ChooseLightSquareColor:\r
-      if (ChangeColor(hDlg, &lsc)) \r
+      if (ChangeColor(hDlg, &lsc))\r
        PaintColorBlock(hDlg, OPT_LightSquareColor, lsc);\r
        PaintSampleSquare(hDlg, OPT_SampleLightSquare, lsc, wpc, hsc, bpc,\r
            TRUE, mono, pieces);\r
       break;\r
 \r
     case OPT_ChooseDarkSquareColor:\r
-      if (ChangeColor(hDlg, &dsc)) \r
+      if (ChangeColor(hDlg, &dsc))\r
        PaintColorBlock(hDlg, OPT_DarkSquareColor, dsc);\r
        PaintSampleSquare(hDlg, OPT_SampleDarkSquare, dsc, bpc, phc, wpc,\r
            FALSE, mono, pieces);\r
       break;\r
 \r
     case OPT_ChooseWhitePieceColor:\r
-      if (ChangeColor(hDlg, &wpc)) \r
+      if (ChangeColor(hDlg, &wpc))\r
        PaintColorBlock(hDlg, OPT_WhitePieceColor, wpc);\r
        PaintSampleSquare(hDlg, OPT_SampleLightSquare, lsc, wpc, hsc, bpc,\r
            TRUE, mono, pieces);\r
       break;\r
 \r
     case OPT_ChooseBlackPieceColor:\r
-      if (ChangeColor(hDlg, &bpc)) \r
+      if (ChangeColor(hDlg, &bpc))\r
        PaintColorBlock(hDlg, OPT_BlackPieceColor, bpc);\r
        PaintSampleSquare(hDlg, OPT_SampleDarkSquare, dsc, bpc, phc, wpc,\r
            FALSE, mono, pieces);\r
       break;\r
 \r
     case OPT_ChooseHighlightSquareColor:\r
-      if (ChangeColor(hDlg, &hsc)) \r
+      if (ChangeColor(hDlg, &hsc))\r
        PaintColorBlock(hDlg, OPT_HighlightSquareColor, hsc);\r
        PaintSampleSquare(hDlg, OPT_SampleLightSquare, lsc, wpc, hsc, bpc,\r
            TRUE, mono, pieces);\r
       break;\r
 \r
     case OPT_ChoosePremoveHighlightColor:\r
-      if (ChangeColor(hDlg, &phc)) \r
+      if (ChangeColor(hDlg, &phc))\r
        PaintColorBlock(hDlg, OPT_PremoveHighlightColor, phc);\r
        PaintSampleSquare(hDlg, OPT_SampleDarkSquare, dsc, bpc, phc, wpc,\r
            FALSE, mono, pieces);\r
@@ -908,7 +908,7 @@ NewVariantDialog(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
   case WM_COMMAND: /* message: received a command */\r
     switch (LOWORD(wParam)) {\r
     case IDOK:\r
-      /* \r
+      /*\r
        * if we call EndDialog() after the call to ChangeBoardSize(),\r
        * then ChangeBoardSize() does not take effect, although the new\r
        * boardSize is saved. Go figure...\r
@@ -916,16 +916,17 @@ NewVariantDialog(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
       EndDialog(hDlg, TRUE);\r
 \r
       v = VariantWhichRadio(hDlg);\r
-      if(!appData.noChessProgram) { char *name = VariantName(v), buf[MSG_SIZ];\r
+      if(!appData.noChessProgram) {\r
+       char *name = VariantName(v), buf[MSG_SIZ];\r
        if (first.protocolVersion > 1 && StrStr(first.variants, name) == NULL) {\r
-           /* [HGM] in protocol 2 we check if variant is suported by engine */\r
-           sprintf(buf, _("Variant %s not supported by %s"), name, first.tidy);\r
-           DisplayError(buf, 0);\r
-           return TRUE; /* treat as _("Cancel") if first engine does not support it */\r
+         /* [HGM] in protocol 2 we check if variant is suported by engine */\r
+         snprintf(buf, MSG_SIZ, _("Variant %s not supported by %s"), name, first.tidy);\r
+         DisplayError(buf, 0);\r
+         return TRUE; /* treat as _("Cancel") if first engine does not support it */\r
        } else\r
        if (second.initDone && second.protocolVersion > 1 && StrStr(second.variants, name) == NULL) {\r
-           sprintf(buf, _("Warning: second engine (%s) does not support this!"), second.tidy);\r
-           DisplayError(buf, 0);   /* use of second engine is optional; only warn user */\r
+         snprintf(buf, MSG_SIZ, r_("Warning: second engine (%s) does not support this!"), second.tidy);\r
+         DisplayError(buf, 0);   /* use of second engine is optional; only warn user */\r
        }\r
       }\r
 \r
@@ -1038,12 +1039,12 @@ UpdateSampleText(HWND hDlg, int id, MyColorizeAttribs *mca)
 {\r
   CHARFORMAT cf;\r
   cf.cbSize = sizeof(CHARFORMAT);\r
-  cf.dwMask = \r
+  cf.dwMask =\r
     CFM_COLOR|CFM_CHARSET|CFM_BOLD|CFM_ITALIC|CFM_UNDERLINE|CFM_STRIKEOUT|CFM_FACE|CFM_SIZE;\r
   cf.crTextColor = mca->color;\r
   cf.dwEffects = mca->effects;\r
   safeStrCpy(cf.szFaceName, font[boardSize][CONSOLE_FONT]->mfp.faceName, sizeof(cf.szFaceName)/sizeof(cf.szFaceName[0]) );\r
-  /* \r
+  /*\r
    * The 20.0 below is in fact documented. yHeight is expressed in twips.\r
    * A twip is 1/20 of a font's point size. See documentation of CHARFORMAT.\r
    * --msw\r
@@ -1075,8 +1076,8 @@ ColorizeTextDialog(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
     CheckDlgButton(hDlg, OPT_Strikeout, (mca.effects & CFE_STRIKEOUT) != 0);\r
 \r
     /* get the current background color from the parent window */\r
-    SendMessage(GetWindow(hDlg, GW_OWNER),WM_COMMAND, \r
-               (WPARAM)WM_USER_GetConsoleBackground, \r
+    SendMessage(GetWindow(hDlg, GW_OWNER),WM_COMMAND,\r
+               (WPARAM)WM_USER_GetConsoleBackground,\r
                (LPARAM)&background);\r
 \r
     /* set the background color */\r
@@ -1099,7 +1100,7 @@ ColorizeTextDialog(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
        cf.cbSize = sizeof(CHARFORMAT);\r
        cf.dwMask = CFM_COLOR;\r
        cf.crTextColor = mca.color;\r
-       SendDlgItemMessage(hwndConsole, OPT_ConsoleInput, \r
+       SendDlgItemMessage(hwndConsole, OPT_ConsoleInput,\r
          EM_SETCHARFORMAT, SCF_ALL, (LPARAM)&cf);\r
       }\r
       EndDialog(hDlg, TRUE);\r
@@ -1203,7 +1204,7 @@ IcsOptionsDialog(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
 \r
 #undef CHECK_BOX\r
 \r
-    sprintf(buf, "%d", appData.icsAlarmTime / 1000);\r
+    snprintf(buf, MSG_SIZ, "%d", appData.icsAlarmTime / 1000);\r
     SetDlgItemText(hDlg, OPT_IcsAlarmTime, buf);\r
     SetDlgItemText(hDlg, OPT_PremoveWhiteText, appData.premoveWhiteText);\r
     SetDlgItemText(hDlg, OPT_PremoveBlackText, appData.premoveBlackText);\r
@@ -1248,7 +1249,7 @@ IcsOptionsDialog(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
   case WM_COMMAND: /* message: received a command */\r
     switch (LOWORD(wParam)) {\r
 \r
-    case WM_USER_GetConsoleBackground: \r
+    case WM_USER_GetConsoleBackground:\r
       /* the ColorizeTextDialog needs the current background color */\r
       colorref = (COLORREF *)lParam;\r
       *colorref = cbc;\r
@@ -1313,20 +1314,20 @@ IcsOptionsDialog(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
        cf.dwMask = CFM_COLOR;\r
        cf.crTextColor = ParseColorName(COLOR_NORMAL);\r
 \r
-       SendDlgItemMessage(hwndConsole, OPT_ConsoleInput, \r
+       SendDlgItemMessage(hwndConsole, OPT_ConsoleInput,\r
          EM_SETCHARFORMAT, SCF_ALL, (LPARAM)&cf);\r
-        SendDlgItemMessage(hwndConsole, OPT_ConsoleText, \r
+        SendDlgItemMessage(hwndConsole, OPT_ConsoleText,\r
          EM_SETBKGNDCOLOR, FALSE, background);\r
-       SendDlgItemMessage(hwndConsole, OPT_ConsoleInput, \r
+       SendDlgItemMessage(hwndConsole, OPT_ConsoleInput,\r
          EM_SETBKGNDCOLOR, FALSE, background);\r
       }\r
 \r
       if (cbc != consoleBackgroundColor) {\r
        consoleBackgroundColor = cbc;\r
        if (appData.colorize) {\r
-         SendDlgItemMessage(hwndConsole, OPT_ConsoleText, \r
+         SendDlgItemMessage(hwndConsole, OPT_ConsoleText,\r
            EM_SETBKGNDCOLOR, FALSE, consoleBackgroundColor);\r
-         SendDlgItemMessage(hwndConsole, OPT_ConsoleInput, \r
+         SendDlgItemMessage(hwndConsole, OPT_ConsoleInput,\r
            EM_SETBKGNDCOLOR, FALSE, consoleBackgroundColor);\r
        }\r
       }\r
@@ -1355,7 +1356,7 @@ IcsOptionsDialog(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
 \r
     case OPT_ChooseChannel1Color:\r
       ColorizeTextPopup(hDlg, ColorChannel1);\r
-      UpdateSampleText(hDlg, OPT_SampleChannel1, \r
+      UpdateSampleText(hDlg, OPT_SampleChannel1,\r
                       &colorizeAttribs[ColorChannel1]);\r
       break;\r
 \r
@@ -1411,7 +1412,7 @@ IcsOptionsDialog(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
 \r
     case OPT_DefaultColors:\r
       for (i=0; i < NColorClasses - 1; i++)\r
-       ParseAttribs(&mca[i].color, \r
+       ParseAttribs(&mca[i].color,\r
                     &mca[i].effects,\r
                     defaultTextAttribs[i]);\r
 \r
@@ -1476,21 +1477,21 @@ SetSampleFontText(HWND hwnd, int id, const MyFont *mf)
   POINT center;\r
   int len;\r
 \r
-  len = sprintf(buf, "%.0f pt. %s%s%s\n",\r
-               mf->mfp.pointSize, mf->mfp.faceName,\r
-               mf->mfp.bold ? " bold" : "",\r
-               mf->mfp.italic ? " italic" : "");\r
+  len = snprintf(buf, MSG_SIZ, "%.0f pt. %s%s%s\n",\r
+                mf->mfp.pointSize, mf->mfp.faceName,\r
+                mf->mfp.bold ? " bold" : "",\r
+                mf->mfp.italic ? " italic" : "");\r
   SetDlgItemText(hwnd, id, buf);\r
 \r
   hControl = GetDlgItem(hwnd, id);\r
   hdc = GetDC(hControl);\r
   SetMapMode(hdc, MM_TEXT);    /* 1 pixel == 1 logical unit */\r
   oldFont = SelectObject(hdc, mf->hf);\r
-  \r
+\r
   /* get number of logical units necessary to display font name */\r
   GetTextExtentPoint32(hdc, buf, len, &size);\r
 \r
-  /* calculate formatting rectangle in the rich edit control.  \r
+  /* calculate formatting rectangle in the rich edit control.\r
    * May be larger or smaller than the actual control.\r
    */\r
   GetClientRect(hControl, &rectClient);\r
@@ -1616,7 +1617,7 @@ FontOptionsDialog(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
 \r
       if (commentDialog) {\r
        SendDlgItemMessage(commentDialog, OPT_CommentText,\r
-         WM_SETFONT, (WPARAM)font[boardSize][COMMENT_FONT]->hf, \r
+         WM_SETFONT, (WPARAM)font[boardSize][COMMENT_FONT]->hf,\r
          MAKELPARAM(TRUE, 0));\r
        GetClientRect(GetDlgItem(commentDialog, OPT_CommentText), &rect);\r
        InvalidateRect(commentDialog, &rect, TRUE);\r
@@ -1624,7 +1625,7 @@ FontOptionsDialog(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
 \r
       if (editTagsDialog) {\r
        SendDlgItemMessage(editTagsDialog, OPT_TagsText,\r
-         WM_SETFONT, (WPARAM)font[boardSize][EDITTAGS_FONT]->hf, \r
+         WM_SETFONT, (WPARAM)font[boardSize][EDITTAGS_FONT]->hf,\r
          MAKELPARAM(TRUE, 0));\r
        GetClientRect(GetDlgItem(editTagsDialog, OPT_TagsText), &rect);\r
        InvalidateRect(editTagsDialog, &rect, TRUE);\r
@@ -1632,7 +1633,7 @@ FontOptionsDialog(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
 \r
       if( moveHistoryDialog != NULL ) {\r
        SendDlgItemMessage(moveHistoryDialog, IDC_MoveHistory,\r
-         WM_SETFONT, (WPARAM)font[boardSize][MOVEHISTORY_FONT]->hf, \r
+         WM_SETFONT, (WPARAM)font[boardSize][MOVEHISTORY_FONT]->hf,\r
          MAKELPARAM(TRUE, 0));\r
         SendMessage( moveHistoryDialog, WM_INITDIALOG, 0, 0 );\r
 //     InvalidateRect(editTagsDialog, NULL, TRUE); // [HGM] this ws improperly cloned?\r
@@ -1640,10 +1641,10 @@ FontOptionsDialog(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
 \r
       if( engineOutputDialog != NULL ) {\r
        SendDlgItemMessage(engineOutputDialog, IDC_EngineMemo1,\r
-         WM_SETFONT, (WPARAM)font[boardSize][MOVEHISTORY_FONT]->hf, \r
+         WM_SETFONT, (WPARAM)font[boardSize][MOVEHISTORY_FONT]->hf,\r
          MAKELPARAM(TRUE, 0));\r
        SendDlgItemMessage(engineOutputDialog, IDC_EngineMemo2,\r
-         WM_SETFONT, (WPARAM)font[boardSize][MOVEHISTORY_FONT]->hf, \r
+         WM_SETFONT, (WPARAM)font[boardSize][MOVEHISTORY_FONT]->hf,\r
          MAKELPARAM(TRUE, 0));\r
       }\r
 \r
@@ -1796,7 +1797,7 @@ InitSoundCombo(HWND hwndCombo, SoundComboData *scd)
   while (scd->label) {\r
     err = SendMessage(hwndCombo, CB_ADDSTRING, 0, (LPARAM) T_(scd->label));\r
     if (err != cnt++) {\r
-      sprintf(buf, "InitSoundCombo(): err '%d', cnt '%d'\n",\r
+      snprintf(buf, MSG_SIZ,  "InitSoundCombo(): err '%d', cnt '%d'\n",\r
          (int)err, (int)cnt);\r
       MessageBox(NULL, buf, NULL, MB_OK);\r
     }\r
@@ -1857,7 +1858,7 @@ void
 DisplaySelectedSound(HWND hDlg, HWND hCombo, const char *name)\r
 {\r
   int radio;\r
-  /* \r
+  /*\r
    * I think it's best to clear the combo and edit boxes. It looks stupid\r
    * to have a value from another sound event sitting there grayed out.\r
    */\r
@@ -1883,7 +1884,7 @@ DisplaySelectedSound(HWND hDlg, HWND hCombo, const char *name)
       radio = OPT_NoSound;\r
     } else {\r
       radio = OPT_BuiltInSound;\r
-      if (SendMessage(hCombo, CB_SELECTSTRING, (WPARAM) -1, \r
+      if (SendMessage(hCombo, CB_SELECTSTRING, (WPARAM) -1,\r
                      (LPARAM) (name + 1)) == CB_ERR) {\r
        SendMessage(hCombo, CB_SETCURSEL, (WPARAM) -1, (LPARAM) 0);\r
        SendMessage(hCombo, WM_SETTEXT, (WPARAM) 0, (LPARAM) (name + 1));\r
@@ -1898,7 +1899,7 @@ DisplaySelectedSound(HWND hDlg, HWND hCombo, const char *name)
   SoundDialogSetEnables(hDlg, radio);\r
   CheckRadioButton(hDlg, OPT_NoSound, OPT_WavFile, radio);\r
 }\r
-    \r
+\r
 \r
 char *builtInSoundNames[] = BUILT_IN_SOUND_NAMES;\r
 \r
@@ -1940,16 +1941,16 @@ SoundOptionsDialog(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
 \r
   case WM_COMMAND: /* message: received a command */\r
 \r
-    if (((HWND)lParam == hSoundCombo) && \r
+    if (((HWND)lParam == hSoundCombo) &&\r
        (HIWORD(wParam) == CBN_SELCHANGE)) {\r
-      /* \r
+      /*\r
        * the user has selected a new sound event. We must store the name for\r
        * the previously selected event, then retrieve the name for the\r
-       * newly selected event and update the dialog. \r
+       * newly selected event and update the dialog.\r
        */\r
       radio = SoundDialogWhichRadio(hDlg);\r
       newName = strdup(SoundDialogGetName(hDlg, radio));\r
-      \r
+\r
       if (strcmp(newName, soundComboData[index].name) != 0) {\r
        free(soundComboData[index].name);\r
        soundComboData[index].name = newName;\r
@@ -1960,13 +1961,13 @@ SoundOptionsDialog(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
       /* now get the settings for the newly selected event */\r
       index = SendMessage(hSoundCombo, CB_GETCURSEL, (WPARAM)0, (LPARAM)0);\r
       DisplaySelectedSound(hDlg, hBISN, soundComboData[index].name);\r
-      \r
+\r
       return TRUE;\r
     }\r
     switch (LOWORD(wParam)) {\r
     case IDOK:\r
-      /* \r
-       * save the name for the currently selected sound event \r
+      /*\r
+       * save the name for the currently selected sound event\r
        */\r
       radio = SoundDialogWhichRadio(hDlg);\r
       newName = strdup(SoundDialogGetName(hDlg, radio));\r
@@ -1990,7 +1991,7 @@ SoundOptionsDialog(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
       }\r
       for ( cc = (ColorClass)0; cc < NColorClasses - 2; cc++) {\r
        index = (int)cc + (int)NSoundClasses;\r
-       if (strcmp(soundComboData[index].name, \r
+       if (strcmp(soundComboData[index].name,\r
                   textAttribs[cc].sound.name) != 0) {\r
          free(textAttribs[cc].sound.name);\r
          textAttribs[cc].sound.name = strdup(soundComboData[index].name);\r
@@ -2171,7 +2172,7 @@ VOID PrintCommSettings(FILE *f, char *name, DCB *dcb)
 {\r
   char *flow = "??", *parity = "??", *stopBits = "??";\r
   ComboData *cd;\r
-  \r
+\r
   cd = cdParity;\r
   while (cd->label != NULL) {\r
     if (dcb->Parity == cd->value) {\r
@@ -2261,7 +2262,7 @@ CommPortOptionsDialog(HWND hDlg, UINT message, WPARAM wParam,     LPARAM lParam)
 \r
     hwndCombo = GetDlgItem(hDlg, OPT_DataRate);\r
     InitCombo(hwndCombo, cdDataRate);\r
-    sprintf(buf, "%u", (int)dcb.BaudRate);\r
+    snprintf(buf, MSG_SIZ, "%u", (int)dcb.BaudRate);\r
     if (SendMessage(hwndCombo, CB_SELECTSTRING, (WPARAM) -1, (LPARAM) buf) == CB_ERR) {\r
       SendMessage(hwndCombo, CB_SETCURSEL, (WPARAM) -1, (LPARAM) 0);\r
       SendMessage(hwndCombo, WM_SETTEXT, (WPARAM) 0, (LPARAM) buf);\r
@@ -2367,7 +2368,7 @@ CommPortOptionsDialog(HWND hDlg, UINT message, WPARAM wParam,     LPARAM lParam)
       }\r
       if (!SetCommState(hCommPort, (LPDCB) &dcb)) {\r
        err = GetLastError();\r
-       switch(MessageBox(hDlg, \r
+       switch(MessageBox(hDlg,\r
                         "Failed to set comm port state;\r\ninvalid options?",\r
                         _("Option Error"), MB_ABORTRETRYIGNORE|MB_ICONQUESTION)) {\r
        case IDABORT:\r
@@ -2436,7 +2437,7 @@ LoadOptions(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
     /* Initialize the dialog items */\r
     if (appData.timeDelay >= 0.0) {\r
       CheckDlgButton(hDlg, OPT_Autostep, TRUE);\r
-      sprintf(buf, "%.2g", appData.timeDelay);\r
+      snprintf(buf, MSG_SIZ, "%.2g", appData.timeDelay);\r
       SetDlgItemText(hDlg, OPT_ASTimeDelay, buf);\r
     } else {\r
       CheckDlgButton(hDlg, OPT_Autostep, FALSE);\r
@@ -2476,7 +2477,7 @@ LoadOptions(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
 }\r
 \r
 \r
-VOID \r
+VOID\r
 LoadOptionsPopup(HWND hwnd)\r
 {\r
   FARPROC lpProc = MakeProcInstance((FARPROC)LoadOptions, hInst);\r
@@ -2584,9 +2585,9 @@ SaveOptionsDialog(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
       return TRUE;\r
 \r
     case OPT_AVBrowse:\r
-      f = OpenFileDialog(hDlg, "a", NULL, \r
-                        appData.oldSaveStyle ? "gam" : "pgn", \r
-                        GAME_FILT, _("Browse for Auto Save File"), \r
+      f = OpenFileDialog(hDlg, "a", NULL,\r
+                        appData.oldSaveStyle ? "gam" : "pgn",\r
+                        GAME_FILT, _("Browse for Auto Save File"),\r
                         NULL, NULL, buf);\r
       if (f != NULL) {\r
        fclose(f);\r
@@ -2975,7 +2976,7 @@ LRESULT CALLBACK UciOptionsDialog(HWND hDlg, UINT message, WPARAM wParam, LPARAM
 \r
     case IDC_BrowseForBook:\r
       {\r
-          char filter[] = { \r
+          char filter[] = {\r
               'A','l','l',' ','F','i','l','e','s', 0,\r
               '*','.','*', 0,\r
               'B','I','N',' ','F','i','l','e','s', 0,\r
index a250e2e..a5d6ce6 100644 (file)
@@ -1,7 +1,7 @@
 /*\r
  * Engine-settings dialog. The complexity come from an attempt to present the engine-defined options\r
  * in a nicey formatted layout. To this end we first run a back-end pre-formatter, which will distribute\r
- * the controls over two columns (the minimum required, as some are double width). It also takes care of \r
+ * the controls over two columns (the minimum required, as some are double width). It also takes care of\r
  * grouping options that start with the same word (mainly for "Polyglot ..." options). It assigns relative\r
  * suitability to break points between lines, and in the end decides if and where to break up the list\r
  * for display in multiple (2*N) columns.\r
@@ -104,7 +104,7 @@ LayoutOptions(int firstOption, int endOption, char *groupName, Option *optionLis
            nextOption++;\r
        }\r
        // We now must be at the end, or looking at a spin or textbox (in nextType)\r
-       if(!stop) \r
+       if(!stop)\r
            nextType = Button; // kudge to flush remaining checks and combos undistorted\r
        // Take a new line if a spin follows combos or checks, or when we encounter a textbox\r
        if((combos+checks || nextType == TextBox) && layout&1) {\r
@@ -122,7 +122,7 @@ LayoutOptions(int firstOption, int endOption, char *groupName, Option *optionLis
        if(nextType == TextBox && lastType == ComboBox)\r
            checkList[checks++] = comboList[--combos];\r
        // Now append the checks behind the (remaining) combos to treat them as one group\r
-       for(i=0; i< checks; i++) \r
+       for(i=0; i< checks; i++)\r
            comboList[combos++] = checkList[i];\r
        // emit the consecutive checks and combos in two columns\r
        right = combos/2; // rounded down if odd!\r
@@ -189,7 +189,7 @@ DesignOptionDialog(ChessProgramState *cps)
                    if( cps->option[k].name[j] != cps->option[k+groupSize].name[j]) break;\r
                groupNameLength = j;\r
                groupSize++;\r
-               \r
+\r
        }\r
        if(groupSize > 3) {\r
                // We found a group to terminates the current section\r
@@ -203,7 +203,7 @@ DesignOptionDialog(ChessProgramState *cps)
     }\r
     if(n != k) LayoutOptions(n, k, "", cps->option); // flush remaining solitary options\r
     // decide if and where we break into two column pairs\r
-    \r
+\r
     // Emit buttons and add OK and cancel\r
 //    for(k=0; k<buttons; k++) layoutList[layout++] = buttonList[k];\r
     // Create the dialog window\r
@@ -281,10 +281,10 @@ SetOptionValues(HWND hDlg, ChessProgramState *cps)
     }\r
     SetDlgItemText( hDlg, IDOK, _("OK") );\r
     SetDlgItemText( hDlg, IDCANCEL, _("Cancel") );\r
-    sprintf(title, _("%s Engine Settings (%s)"), T_(cps->which), cps->tidy); \r
+    snprintf(title, MSG_SIZ, _("%s Engine Settings (%s)"), T_(cps->which), cps->tidy);\r
     title[0] &= ~32; // capitalize\r
     SetWindowText( hDlg, title);\r
-    for(i=0; i<groups; i+=2) { \r
+    for(i=0; i<groups; i+=2) {\r
        int id, p; char buf[MSG_SIZ];\r
        id = k = boxList[i];\r
        if(layoutList[k] < 0) k++;\r
@@ -346,8 +346,10 @@ GetOptionValues(HWND hDlg, ChessProgramState *cps)
            default:\r
                break; // are treated instantly, so they have been sent already\r
        }\r
-       if(changed == 2) sprintf(buf, "option %s=%d\n", cps->option[j].name, new); else\r
-       if(changed == 1) sprintf(buf, "option %s=%s\n", cps->option[j].name, newText);\r
+       if(changed == 2)\r
+         snprintf(buf, MSG_SIZ, "option %s=%d\n", cps->option[j].name, new); else\r
+       if(changed == 1)\r
+         snprintf(buf, MSG_SIZ, "option %s=%s\n", cps->option[j].name, newText);\r
        if(changed) SendToProgram(buf, cps);\r
     }\r
 }\r
@@ -376,7 +378,7 @@ LRESULT CALLBACK SettingsProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lPa
             return TRUE;\r
 \r
         case IDCANCEL:\r
-            EndDialog( hDlg, 1 );   \r
+            EndDialog( hDlg, 1 );\r
             return TRUE;\r
 \r
        default:\r
@@ -385,10 +387,10 @@ LRESULT CALLBACK SettingsProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lPa
            if( i>=2000 &&  i < 2000+2*(layout+buttons)) {\r
                j = layoutList[(i - 2000)/2];\r
                if(j == -2) {\r
-                         char filter[] = \r
+                         char filter[] =\r
                                "All files\0*.*\0BIN Files\0*.bin\0LOG Files\0*.log\0INI Files\0*.ini\0\0";\r
 /*\r
-{ \r
+{\r
                              'A','l','l',' ','F','i','l','e','s', 0,\r
                              '*','.','*', 0,\r
                              'B','I','N',' ','F','i','l','e','s', 0,\r
@@ -418,7 +420,7 @@ LRESULT CALLBACK SettingsProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lPa
                if( activeCps->option[j].type  == SaveButton)\r
                     GetOptionValues(hDlg, activeCps);\r
                else if( activeCps->option[j].type  != Button) break;\r
-               sprintf(buf, "option %s\n", activeCps->option[j].name);\r
+               snprintf(buf, MSG_SIZ, "option %s\n", activeCps->option[j].name);\r
                SendToProgram(buf, activeCps);\r
            }\r
            break;\r
@@ -484,7 +486,7 @@ void AddOption(int x, int y, Control type, int i)
        case Message:\r
            break;\r
     }\r
-    \r
+\r
 }\r
 \r
 void\r
@@ -495,7 +497,7 @@ CreateDialogTemplate(int *layoutList, int nr, ChessProgramState *cps)
     template.header.cdit = 0;\r
     template.header.cx = 307;\r
     buttonRows = (buttons + 1 + 3)/4; // 4 per row, rounded up\r
-    if(nr > 50) { \r
+    if(nr > 50) {\r
        breakPoint = (nr+2*buttonRows+1)/2 & ~1;\r
        template.header.cx = 625;\r
     }\r
@@ -503,9 +505,9 @@ CreateDialogTemplate(int *layoutList, int nr, ChessProgramState *cps)
     for(i=0; i<nr; i++) {\r
        if(k < groups && i == boxList[k]) {\r
            y += 10;\r
-           AddControl(x+2, y+13*(i>>1)-2, 301, 13*(boxList[k+1]-boxList[k]>>1)+8, \r
+           AddControl(x+2, y+13*(i>>1)-2, 301, 13*(boxList[k+1]-boxList[k]>>1)+8,\r
                                                0x0082, WS_VISIBLE | WS_CHILD | SS_BLACKFRAME, 2400);\r
-           AddControl(x+60, y+13*(i>>1)-6, 10*groupNameList[k]/3, 10, \r
+           AddControl(x+60, y+13*(i>>1)-6, 10*groupNameList[k]/3, 10,\r
                                                0x0082, SS_ENDELLIPSIS | WS_VISIBLE | WS_CHILD, 2*(i+MAX_OPTIONS));\r
        }\r
        j = layoutList[i];\r
@@ -530,7 +532,7 @@ CreateDialogTemplate(int *layoutList, int nr, ChessProgramState *cps)
     template.header.style &= ~WS_VSCROLL;\r
 }\r
 \r
-void \r
+void\r
 EngineOptionsPopup(HWND hwnd, ChessProgramState *cps)\r
 {\r
     FARPROC lpProc = MakeProcInstance( (FARPROC) SettingsProc, hInst );\r
index 849ab40..e9925ae 100644 (file)
--- a/xboard.c
+++ b/xboard.c
@@ -1594,8 +1594,9 @@ ConvertToLine(int argc, char **argv)
   for(i=1; i<argc; i++) {
     if( (strchr(argv[i], ' ') || strchr(argv[i], '\n') ||strchr(argv[i], '\t') )
        && argv[i][0] != '{' )
-         sprintf(buf, "{%s} ", argv[i]);
-    else sprintf(buf, "%s ", argv[i]);
+      snprintf(buf, sizeof(buf)/sizeof(buf[0]), "{%s} ", argv[i]);
+    else
+      snprintf(buf, sizeof(buf)/sizeof(buf[0]), "%s ", argv[i]);
     strcat(line, buf);
   }
     line[strlen(line)-1] = NULLCHAR;
@@ -3002,7 +3003,7 @@ FindFont(pattern, targetPxlSize)
     XFontStruct **fnt_list;
 
     base_fnt_lst = calloc(1, strlen(pattern) + 3);
-    sprintf(strInt, "%d", targetPxlSize);
+    snprintf(strInt, sizeof(strInt)/sizeof(strInt[0]), "%d", targetPxlSize);
     p = strstr(pattern, "--");
     strncpy(base_fnt_lst, pattern, p - pattern + 2);
     strcat(base_fnt_lst, strInt);
@@ -3502,12 +3503,12 @@ void CreatePieces()
 
     for (kind = SOLID; kind <= (appData.monoMode ? OUTLINE : SOLID); kind++) {
        for (piece = (int) WhitePawn; piece <= (int) WhiteKing + 4; piece++) {
-           sprintf(buf, "%s%c%u%c.bm", piece > (int)WhiteKing ? "w" : "",
-                   pieceBitmapNames[piece],
-                   ss, kind == SOLID ? 's' : 'o');
-           ReadBitmap(&pieceBitmap2[kind][piece], buf, NULL, ss, ss);
-           if(piece <= (int)WhiteKing)
-               pieceBitmap[kind][piece] = pieceBitmap2[kind][piece];
+         snprintf(buf, MSG_SIZ, "%s%c%u%c.bm", piece > (int)WhiteKing ? "w" : "",
+                  pieceBitmapNames[piece],
+                  ss, kind == SOLID ? 's' : 'o');
+         ReadBitmap(&pieceBitmap2[kind][piece], buf, NULL, ss, ss);
+         if(piece <= (int)WhiteKing)
+           pieceBitmap[kind][piece] = pieceBitmap2[kind][piece];
        }
     }
 
@@ -3530,13 +3531,13 @@ void CreatePieces()
 
     for (kind = SOLID; kind <= (appData.monoMode ? OUTLINE : SOLID); kind++) {
        for (piece = (int) WhitePawn; piece <= (int) WhiteKing + 4; piece++) {
-           sprintf(buf, "%s%c%u%c.bm", piece > (int)WhiteKing ? "w" : "",
-                   pieceBitmapNames[piece],
-                   ss, kind == SOLID ? 's' : 'o');
-           ReadBitmap(&pieceBitmap2[kind][piece], buf,
-                      bib->bits[kind][piece], ss, ss);
-           if(piece <= (int)WhiteKing)
-               pieceBitmap[kind][piece] = pieceBitmap2[kind][piece];
+         snprintf(buf, MSG_SIZ, "%s%c%u%c.bm", piece > (int)WhiteKing ? "w" : "",
+                  pieceBitmapNames[piece],
+                  ss, kind == SOLID ? 's' : 'o');
+         ReadBitmap(&pieceBitmap2[kind][piece], buf,
+                    bib->bits[kind][piece], ss, ss);
+         if(piece <= (int)WhiteKing)
+           pieceBitmap[kind][piece] = pieceBitmap2[kind][piece];
        }
     }
 
@@ -5991,7 +5992,7 @@ void AnalyzeModeProc(w, event, prms, nprms)
     /* [DM] icsEngineAnalyze [HGM] This is horrible code; reverse the gameMode and isEngineAnalyze tests! */
     if (appData.icsActive) {
         if (gameMode != IcsObserving) {
-            sprintf(buf,_("You are not observing a game"));
+         snprintf(buf, MSG_SIZ, _("You are not observing a game"));
             DisplayError(buf, 0);
             /* secure check */
             if (appData.icsEngineAnalyze) {
@@ -7433,18 +7434,18 @@ Colorize(cc, continuation)
 
     if (textColors[(int)cc].bg > 0) {
        if (textColors[(int)cc].fg > 0) {
-           sprintf(buf, "\033[0;%d;%d;%dm", textColors[(int)cc].attr,
-                   textColors[(int)cc].fg, textColors[(int)cc].bg);
+         snprintf(buf, MSG_SIZ, "\033[0;%d;%d;%dm", textColors[(int)cc].attr,
+                  textColors[(int)cc].fg, textColors[(int)cc].bg);
        } else {
-           sprintf(buf, "\033[0;%d;%dm", textColors[(int)cc].attr,
-                   textColors[(int)cc].bg);
+         snprintf(buf, MSG_SIZ, "\033[0;%d;%dm", textColors[(int)cc].attr,
+                  textColors[(int)cc].bg);
        }
     } else {
        if (textColors[(int)cc].fg > 0) {
-           sprintf(buf, "\033[0;%d;%dm", textColors[(int)cc].attr,
+         snprintf(buf, MSG_SIZ, "\033[0;%d;%dm", textColors[(int)cc].attr,
                    textColors[(int)cc].fg);
        } else {
-           sprintf(buf, "\033[0;%dm", textColors[(int)cc].attr);
+         snprintf(buf, MSG_SIZ, "\033[0;%dm", textColors[(int)cc].attr);
        }
     }
     count = strlen(buf);
@@ -7713,11 +7714,11 @@ DisplayTimerLabel(w, color, timer, highlight)
       foregroundOrWarningColor = lowTimeWarningColor;
 
     if (appData.clockMode) {
-       sprintf(buf, "%s: %s", color, TimeString(timer));
-       XtSetArg(args[0], XtNlabel, buf);
+      snprintf(buf, MSG_SIZ, "%s: %s", color, TimeString(timer));
+      XtSetArg(args[0], XtNlabel, buf);
     } else {
-       sprintf(buf, "%s  ", color);
-       XtSetArg(args[0], XtNlabel, buf);
+      snprintf(buf, MSG_SIZ, "%s  ", color);
+      XtSetArg(args[0], XtNlabel, buf);
     }
 
     if (highlight) {
index 630903a..92643c1 100644 (file)
@@ -131,11 +131,11 @@ void ShuffleCallback(w, client_data, call_data)
     String name;
     Widget w2;
     Arg args[16];
-    char buf[80];
-    
+    char buf[MSG_SIZ];
+
     XtSetArg(args[0], XtNlabel, &name);
     XtGetValues(w, args, 1);
-    
+
     if (strcmp(name, _("cancel")) == 0) {
         ShufflePopDown();
         return;
@@ -147,7 +147,7 @@ void ShuffleCallback(w, client_data, call_data)
         return;
     }
     if (strcmp(name, _("random")) == 0) {
-       sprintf(buf, "%d", rand());
+      snprintf(buf, MSG_SIZ,  "%d", rand());
        XtSetArg(args[0],XtNvalue, buf); // erase bad (non-numeric) value
        XtSetValues(XtParent(w), args, 1);
         return;
@@ -156,7 +156,7 @@ void ShuffleCallback(w, client_data, call_data)
        int nr; String name;
         name = XawDialogGetValueString(w2 = XtParent(w));
        if(sscanf(name ,"%d",&nr) != 1) {
-           sprintf(buf, "%d", appData.defaultFrcPosition);
+         snprintf(buf, MSG_SIZ,  "%d", appData.defaultFrcPosition);
            XtSetArg(args[0],XtNvalue, buf); // erase bad (non-numeric) value
            XtSetValues(w2, args, 1);
            return;
@@ -177,27 +177,27 @@ void ShufflePopUp()
     int x, y, i;
     int win_x, win_y;
     unsigned int mask;
-    char def[80];
-    
+    char def[MSG_SIZ];
+
     i = 0;
     XtSetArg(args[i], XtNresizable, True); i++;
     XtSetArg(args[i], XtNwidth, DIALOG_SIZE); i++;
     shuffleShell = popup =
       XtCreatePopupShell(_("New Shuffle Game"), transientShellWidgetClass,
                         shellWidget, args, i);
-    
+
     layout =
       XtCreateManagedWidget(layoutName, formWidgetClass, popup,
                            layoutArgs, XtNumber(layoutArgs));
-  
-    sprintf(def, "%d\n", appData.defaultFrcPosition);
+
+    snprintf(def, MSG_SIZ,  "%d\n", appData.defaultFrcPosition);
     i = 0;
     XtSetArg(args[i], XtNlabel, _("Start-position number:")); i++;
     XtSetArg(args[i], XtNvalue, def); i++;
     XtSetArg(args[i], XtNborderWidth, 0); i++;
     dialog = XtCreateManagedWidget(_("Shuffle"), dialogWidgetClass,
                                   layout, args, i);
-    
+
 //    XtSetArg(args[0], XtNeditType, XawtextEdit);  // [HGM] can't get edit to work decently
 //    XtSetArg(args[1], XtNuseStringInPlace, False);
 //    XtSetValues(dialog, args, 2);
@@ -206,20 +206,20 @@ void ShufflePopUp()
     XawDialogAddButton(dialog, _("cancel"), ShuffleCallback, (XtPointer) dialog);
     XawDialogAddButton(dialog, _("random"), ShuffleCallback, (XtPointer) dialog);
     XawDialogAddButton(dialog, _("off"), ShuffleCallback, (XtPointer) dialog);
-    
+
     XtRealizeWidget(popup);
     CatchDeleteWindow(popup, "ShufflePopDown");
-    
+
     XQueryPointer(xDisplay, xBoardWindow, &root, &child,
                  &x, &y, &win_x, &win_y, &mask);
-    
+
     XtSetArg(args[0], XtNx, x - 10);
     XtSetArg(args[1], XtNy, y - 30);
     XtSetValues(popup, args, 2);
-    
+
     XtPopup(popup, XtGrabExclusive);
     shuffleUp = True;
-    
+
     edit = XtNameToWidget(dialog, "*value");
 
     XtSetKeyboardFocus(popup, edit);
@@ -261,12 +261,12 @@ void TimeControlCallback(w, client_data, call_data)
     String name, txt;
     Widget w2;
     Arg args[16];
-    char buf[80];
+    char buf[MSG_SIZ];
     int j;
 
     XtSetArg(args[0], XtNlabel, &name);
     XtGetValues(w, args, 1);
-    
+
     if (strcmp(name, _("classical")) == 0) {
        if(tcInc == 0) return;
        j=0;
@@ -281,7 +281,7 @@ void TimeControlCallback(w, client_data, call_data)
            XtGetValues(tcData, args, j);
            tcIncrement = 0; sscanf(name, "%d", &tcIncrement);
        }
-       sprintf(buf, "%d", tcMoves);
+       snprintf(buf, MSG_SIZ,  "%d", tcMoves);
        j=0;
        XtSetArg(args[j], XtNstring, buf); j++;
        XtSetValues(tcData, args, j);
@@ -302,7 +302,7 @@ void TimeControlCallback(w, client_data, call_data)
            XtGetValues(tcData, args, j);
            tcMoves = appData.movesPerSession; sscanf(name, "%d", &tcMoves);
        }
-       sprintf(buf, "%d", tcIncrement);
+       snprintf(buf, MSG_SIZ,  "%d", tcIncrement);
        j=0;
        XtSetArg(args[j], XtNstring, buf); j++;
        XtSetValues(tcData, args, j);
@@ -369,10 +369,10 @@ void TimeControlCallback(w, client_data, call_data)
        }
        XtSetArg(args[0], XtNstring, &txt);
        XtGetValues(tcOdds1, args, 1);
-       appData.firstTimeOdds = first.timeOdds 
+       appData.firstTimeOdds = first.timeOdds
                = (sscanf(txt, "%d", &j) == 1 && j > 0) ? j : 1;
        XtGetValues(tcOdds2, args, 1);
-       appData.secondTimeOdds = second.timeOdds 
+       appData.secondTimeOdds = second.timeOdds
                = (sscanf(txt, "%d", &j) == 1 && j > 0) ? j : 1;
 
        Reset(True, True);
@@ -389,12 +389,12 @@ void TimeControlPopUp()
     int x, y, i, j;
     int win_x, win_y;
     unsigned int mask;
-    char def[80];
-    
+    char def[MSG_SIZ];
+
     tcInc = searchTime > 0 ? 2 : (appData.timeIncrement >= 0);
     tcMoves = appData.movesPerSession; tcIncrement = appData.timeIncrement;
     if(!tcInc) tcIncrement = 0;
-    sprintf(def, "%d", tcInc ? tcIncrement : tcMoves);
+    snprintf(def, MSG_SIZ,  "%d", tcInc ? tcIncrement : tcMoves);
 
     i = 0;
     XtSetArg(args[i], XtNresizable, True); i++;
@@ -402,15 +402,15 @@ void TimeControlPopUp()
     TimeControlShell = popup =
       XtCreatePopupShell(_("TimeControl Menu"), transientShellWidgetClass,
                         shellWidget, args, i);
-    
+
     layout =
       XtCreateManagedWidget(layoutName, formWidgetClass, popup,
                            layoutArgs, XtNumber(layoutArgs));
-  
+
     form =
       XtCreateManagedWidget(layoutName, formWidgetClass, layout,
                            formArgs, XtNumber(formArgs));
-  
+
     j = 0;
 //    XtSetArg(args[j], XtNwidth,     (XtArgVal) 300); j++;
 //    XtSetArg(args[j], XtNheight,    (XtArgVal) 85); j++;
@@ -532,7 +532,7 @@ void TimeControlPopUp()
     XtSetArg(args[j], XtNright, XtChainLeft);  j++;
     XtSetArg(args[j], XtNstate, tcInc==0); j++;
     b_clas= XtCreateManagedWidget(_("classical"), toggleWidgetClass,
-                                  form, args, j);   
+                                  form, args, j);
     XtAddCallback(b_clas, XtNcallback, TimeControlCallback, (XtPointer) 0);
 
     j=0;
@@ -545,7 +545,7 @@ void TimeControlPopUp()
     XtSetArg(args[j], XtNright, XtChainLeft);  j++;
     XtSetArg(args[j], XtNstate, tcInc==1); j++;
     b_inc = XtCreateManagedWidget(_("incremental"), toggleWidgetClass,
-                                  form, args, j);   
+                                  form, args, j);
     XtAddCallback(b_inc, XtNcallback, TimeControlCallback, (XtPointer) 0);
 
     j=0;
@@ -558,7 +558,7 @@ void TimeControlPopUp()
     XtSetArg(args[j], XtNright, XtChainLeft);  j++;
     XtSetArg(args[j], XtNstate, tcInc==2); j++;
     b_inc = XtCreateManagedWidget(_("fixed time"), toggleWidgetClass,
-                                  form, args, j);   
+                                  form, args, j);
     XtAddCallback(b_inc, XtNcallback, TimeControlCallback, (XtPointer) 0);
 
     j=0;
@@ -569,7 +569,7 @@ void TimeControlPopUp()
     XtSetArg(args[j], XtNleft, XtChainRight);  j++;
     XtSetArg(args[j], XtNright, XtChainRight);  j++;
     b_ok= XtCreateManagedWidget(_(" OK "), commandWidgetClass,
-                                  form, args, j);   
+                                  form, args, j);
     XtAddCallback(b_ok, XtNcallback, TimeControlCallback, (XtPointer) 0);
 
     j=0;
@@ -580,22 +580,22 @@ void TimeControlPopUp()
     XtSetArg(args[j], XtNleft, XtChainRight);  j++;
     XtSetArg(args[j], XtNright, XtChainRight);  j++;
     b_cancel= XtCreateManagedWidget(_("cancel"), commandWidgetClass,
-                                  form, args, j);   
+                                  form, args, j);
     XtAddCallback(b_cancel, XtNcallback, TimeControlPopDown, (XtPointer) 0);
 
     XtRealizeWidget(popup);
     CatchDeleteWindow(popup, "TimeControlPopDown");
-    
+
     XQueryPointer(xDisplay, xBoardWindow, &root, &child,
                  &x, &y, &win_x, &win_y, &mask);
-    
+
     XtSetArg(args[0], XtNx, x - 10);
     XtSetArg(args[1], XtNy, y - 30);
     XtSetValues(popup, args, 2);
-    
+
     XtPopup(popup, XtGrabExclusive);
     TimeControlUp = True;
-    
+
     previous = NULL;
     SetFocus(tcTime, popup, (XEvent*) NULL, False);
 //    XtSetKeyboardFocus(popup, tcTime);
@@ -648,10 +648,10 @@ void EngineCallback(w, client_data, call_data)
     Arg args[16];
     char buf[80];
     int j;
-    
+
     XtSetArg(args[0], XtNlabel, &name);
     XtGetValues(w, args, 1);
-    
+
     if (strcmp(name, _("OK")) == 0) {
        // read all switches
        appData.periodicUpdates = ReadToggle(w1);
@@ -663,7 +663,7 @@ void EngineCallback(w, client_data, call_data)
        appData.materialDraws = ReadToggle(w7);
        appData.trivialDraws  = ReadToggle(w8);
 
-       // adjust setting in other menu for duplicates 
+       // adjust setting in other menu for duplicates
        // (perhaps duplicates should be removed from general Option Menu?)
 //     XtSetArg(args[0], XtNleftBitmap, appData.showThinking ? xMarkPixmap : None);
 //     XtSetValues(XtNameToWidget(menuBarWidget,
@@ -674,7 +674,7 @@ void EngineCallback(w, client_data, call_data)
        XtGetValues(engDrawMoves, args, 1);
        if(sscanf(name, "%d", &j) == 1) appData.adjudicateDrawMoves = j;
        XtGetValues(engThreshold, args, 1);
-       if(sscanf(name, "%d", &j) == 1) 
+       if(sscanf(name, "%d", &j) == 1)
                adjudicateLossThreshold = appData.adjudicateLossThreshold = -j; // inverted!
        XtGetValues(engRule, args, 1);
        if(sscanf(name, "%d", &j) == 1) appData.ruleMoves = j;
@@ -690,17 +690,17 @@ void EngineCallback(w, client_data, call_data)
 void EnginePopUp()
 {
     Arg args[16];
-    Widget popup, layout, form, edit, b_ok, b_cancel, b_clas, b_inc, s1; 
+    Widget popup, layout, form, edit, b_ok, b_cancel, b_clas, b_inc, s1;
     Window root, child;
     int x, y, i, j, width;
     int win_x, win_y;
     unsigned int mask;
-    char def[80];
-    
+    char def[MSG_SIZ];
+
     tcInc = (appData.timeIncrement >= 0);
     tcMoves = appData.movesPerSession; tcIncrement = appData.timeIncrement;
     if(!tcInc) tcIncrement = 0;
-    sprintf(def, "%d", tcInc ? tcIncrement : tcMoves);
+    snprintf(def, MSG_SIZ,  "%d", tcInc ? tcIncrement : tcMoves);
 
     i = 0;
     XtSetArg(args[i], XtNresizable, True); i++;
@@ -708,15 +708,15 @@ void EnginePopUp()
     EngineShell = popup =
       XtCreatePopupShell(_("Adjudications"), transientShellWidgetClass,
                         shellWidget, args, i);
-    
+
     layout =
       XtCreateManagedWidget(layoutName, formWidgetClass, popup,
                            layoutArgs, XtNumber(layoutArgs));
-  
+
     form =
       XtCreateManagedWidget(layoutName, formWidgetClass, layout,
                            formArgs, XtNumber(formArgs));
-  
+
     j = 0;
 //    XtSetArg(args[j], XtNwidth,     (XtArgVal) 250); j++;
 //    XtSetArg(args[j], XtNheight,    (XtArgVal) 400); j++;
@@ -769,7 +769,7 @@ void EnginePopUp()
     XtSetArg(args[1], XtNborderWidth, (XtArgVal) 0);
     XtSetValues(s1, args, 2);
 
-    sprintf(def, "%d", appData.adjudicateDrawMoves);
+    snprintf(def, MSG_SIZ,  "%d", appData.adjudicateDrawMoves);
     j= 0;
     XtSetArg(args[j], XtNborderWidth, 1); j++;
     XtSetArg(args[j], XtNfromVert, w8); j++;
@@ -801,7 +801,7 @@ void EnginePopUp()
 //    XtSetArg(args[j], XtNheight, 20);  j++;
     tcMess1 = XtCreateManagedWidget("TCtext", labelWidgetClass, form, args, j);
 
-    sprintf(def, "%d", -appData.adjudicateLossThreshold); // inverted!
+    snprintf(def, MSG_SIZ,  "%d", -appData.adjudicateLossThreshold); // inverted!
     j= 0;
     XtSetArg(args[j], XtNborderWidth, 1); j++;
     XtSetArg(args[j], XtNfromVert, engDrawMoves); j++;
@@ -833,7 +833,7 @@ void EnginePopUp()
 //    XtSetArg(args[j], XtNheight, 20);  j++;
     tcMess2 = XtCreateManagedWidget("MPStext", labelWidgetClass, form, args, j);
 
-    sprintf(def, "%d", appData.ruleMoves);
+    snprintf(def, MSG_SIZ,  "%d", appData.ruleMoves);
     j= 0;
     XtSetArg(args[j], XtNborderWidth, 1); j++;
     XtSetArg(args[j], XtNfromVert, engThreshold); j++;
@@ -865,7 +865,7 @@ void EnginePopUp()
 //    XtSetArg(args[j], XtNheight, 20);  j++;
     tcMess1 = XtCreateManagedWidget("TCtext", labelWidgetClass, form, args, j);
 
-    sprintf(def, "%d", appData.drawRepeats);
+    snprintf(def, MSG_SIZ,  "%d", appData.drawRepeats);
     j= 0;
     XtSetArg(args[j], XtNborderWidth, 1); j++;
     XtSetArg(args[j], XtNfromVert, engRule); j++;
@@ -904,7 +904,7 @@ void EnginePopUp()
     XtSetArg(args[j], XtNtop, XtChainBottom);  j++;
     XtSetArg(args[j], XtNleft, XtChainRight);  j++;
     XtSetArg(args[j], XtNright, XtChainRight);  j++;
-    b_ok= XtCreateManagedWidget(_("OK"), commandWidgetClass, form, args, j);   
+    b_ok= XtCreateManagedWidget(_("OK"), commandWidgetClass, form, args, j);
     XtAddCallback(b_ok, XtNcallback, EngineCallback, (XtPointer) 0);
 
     j=0;
@@ -915,22 +915,22 @@ void EnginePopUp()
     XtSetArg(args[j], XtNleft, XtChainRight);  j++;
     XtSetArg(args[j], XtNright, XtChainRight);  j++;
     b_cancel= XtCreateManagedWidget(_("cancel"), commandWidgetClass,
-                                  form, args, j);   
+                                  form, args, j);
     XtAddCallback(b_cancel, XtNcallback, EnginePopDown, (XtPointer) 0);
 
     XtRealizeWidget(popup);
     CatchDeleteWindow(popup, "EnginePopDown");
-    
+
     XQueryPointer(xDisplay, xBoardWindow, &root, &child,
                  &x, &y, &win_x, &win_y, &mask);
-    
+
     XtSetArg(args[0], XtNx, x - 10);
     XtSetArg(args[1], XtNy, y - 30);
     XtSetValues(popup, args, 2);
-    
+
     XtPopup(popup, XtGrabExclusive);
     EngineUp = True;
-    
+
     previous = NULL;
     SetFocus(engThreshold, popup, (XEvent*) NULL, False);
 }
@@ -1006,27 +1006,27 @@ void NewVariantCallback(w, client_data, call_data)
     String name;
     Widget w2;
     Arg args[16];
-    char buf[80];
+    char buf[MSG_SIZ];
     VariantClass v;
-    
+
     XtSetArg(args[0], XtNlabel, &name);
     XtGetValues(w, args, 1);
-    
+
     if (strcmp(name, _("  OK  ")) == 0) {
        int nr = (intptr_t) XawToggleGetCurrent(buttonDesc[0].handle) - 1;
        if(nr < 0) return;
        v = buttonDesc[nr].variant;
-       if(!appData.noChessProgram) { 
+       if(!appData.noChessProgram) {
            char *name = VariantName(v), buf[MSG_SIZ];
            if (first.protocolVersion > 1 && StrStr(first.variants, name) == NULL) {
                /* [HGM] in protocol 2 we check if variant is suported by engine */
-               sprintf(buf, _("Variant %s not supported by %s"), name, first.tidy);
+             snprintf(buf, MSG_SIZ,  _("Variant %s not supported by %s"), name, first.tidy);
                DisplayError(buf, 0);
 //             NewVariantPopDown();
                return; /* ignore OK if first engine does not support it */
            } else
            if (second.initDone && second.protocolVersion > 1 && StrStr(second.variants, name) == NULL) {
-               sprintf(buf, _("Warning: second engine (%s) does not support this!"), second.tidy);
+             snprintf(buf, MSG_SIZ,  _("Warning: second engine (%s) does not support this!"), second.tidy);
                DisplayError(buf, 0);   /* use of second engine is optional; only warn user */
            }
        }
@@ -1061,15 +1061,15 @@ void NewVariantPopUp()
     NewVariantShell = popup =
       XtCreatePopupShell(_("NewVariant Menu"), transientShellWidgetClass,
                         shellWidget, args, i);
-    
+
     layout =
       XtCreateManagedWidget(layoutName, formWidgetClass, popup,
                            layoutArgs, XtNumber(layoutArgs));
-  
+
     form =
       XtCreateManagedWidget("form", formWidgetClass, layout,
                            formArgs, XtNumber(formArgs));
-  
+
     for(i = 0; buttonDesc[i].name != NULL; i++) {
        Pixel buttonColor;
        if (!appData.monoMode) {
@@ -1082,7 +1082,7 @@ void NewVariantPopUp()
                buttonColor = *(Pixel *) vTo.addr;
            }
        }
-    
+
        j = 0;
        XtSetArg(args[j], XtNradioGroup, last); j++;
        XtSetArg(args[j], XtNwidth, 125); j++;
@@ -1105,7 +1105,7 @@ void NewVariantPopUp()
     XtSetArg(args[j], XtNtop, XtChainBottom);  j++;
     XtSetArg(args[j], XtNleft, XtChainRight);  j++;
     XtSetArg(args[j], XtNright, XtChainRight);  j++;
-    b_cancel= XtCreateManagedWidget(_("CANCEL"), commandWidgetClass, form, args, j);   
+    b_cancel= XtCreateManagedWidget(_("CANCEL"), commandWidgetClass, form, args, j);
     XtAddCallback(b_cancel, XtNcallback, NewVariantPopDown, (XtPointer) 0);
 
     j=0;
@@ -1117,7 +1117,7 @@ void NewVariantPopUp()
     XtSetArg(args[j], XtNtop, XtChainBottom);  j++;
     XtSetArg(args[j], XtNleft, XtChainRight);  j++;
     XtSetArg(args[j], XtNright, XtChainRight);  j++;
-    b_ok= XtCreateManagedWidget(_("  OK  "), commandWidgetClass, form, args, j);   
+    b_ok= XtCreateManagedWidget(_("  OK  "), commandWidgetClass, form, args, j);
     XtAddCallback(b_ok, XtNcallback, NewVariantCallback, (XtPointer) 0);
 
     j=0;
@@ -1136,14 +1136,14 @@ void NewVariantPopUp()
 
            XtRealizeWidget(popup);
     CatchDeleteWindow(popup, "NewVariantPopDown");
-    
+
     XQueryPointer(xDisplay, xBoardWindow, &root, &child,
                  &x, &y, &win_x, &win_y, &mask);
-    
+
     XtSetArg(args[0], XtNx, x - 10);
     XtSetArg(args[1], XtNy, y - 30);
     XtSetValues(popup, args, 2);
-    
+
     XtPopup(popup, XtGrabExclusive);
     NewVariantUp = True;
 }
@@ -1195,10 +1195,10 @@ void UciCallback(w, client_data, call_data)
     Arg args[16];
     char buf[80];
     int oldCores = appData.smpCores, ponder = 0;
-    
+
     XtSetArg(args[0], XtNlabel, &name);
     XtGetValues(w, args, 1);
-    
+
     if (strcmp(name, _("OK")) == 0) {
        int nr, i, j; String name;
        for(i=0; i<6; i++) {
@@ -1208,7 +1208,7 @@ void UciCallback(w, client_data, call_data)
                if(name)
                    *(char**) controlDesc[i].ptr = strdup(name);
            } else {
-               if(sscanf(name, "%d", &j) == 1) 
+               if(sscanf(name, "%d", &j) == 1)
                    *(int*) controlDesc[i].ptr = j;
            }
        }
@@ -1221,7 +1221,7 @@ void UciCallback(w, client_data, call_data)
        XtSetArg(args[0], XtNstate, &ponder);
        XtGetValues(w4, args, 1);
 
-       // adjust setting in other menu for duplicates 
+       // adjust setting in other menu for duplicates
        // (perhaps duplicates should be removed from general Option Menu?)
        XtSetArg(args[0], XtNleftBitmap, ponder ? xMarkPixmap : None);
        XtSetValues(XtNameToWidget(menuBarWidget,
@@ -1248,24 +1248,24 @@ void UciPopUp()
     int x, y, i, j;
     int win_x, win_y;
     unsigned int mask;
-    char def[80];
-    
+    char def[MSG_SIZ];
+
     i = 0;
     XtSetArg(args[i], XtNresizable, True); i++;
 //    XtSetArg(args[i], XtNwidth, 300); i++;
     UciShell = popup =
       XtCreatePopupShell(_("Engine Settings"), transientShellWidgetClass,
                         shellWidget, args, i);
-    
+
     layout =
       XtCreateManagedWidget(layoutName, formWidgetClass, popup,
                            layoutArgs, XtNumber(layoutArgs));
-  
-    
+
+
     form =
       XtCreateManagedWidget("form", formWidgetClass, layout,
                            formArgs, XtNumber(formArgs));
-  
+
     j = 0;
     XtSetArg(args[j], XtNtop, XtChainTop);  j++;
     XtSetArg(args[j], XtNbottom, XtChainTop);  j++;
@@ -1291,10 +1291,10 @@ void UciPopUp()
        XtSetArg(args[j], XtNwidth, i&1 ? 245 : 50); j++;
        XtSetArg(args[j], XtNinsertPosition, 9999);  j++;
        if(i&1) {
-           XtSetArg(args[j], XtNstring, * (char**) controlDesc[i].ptr ? 
+           XtSetArg(args[j], XtNstring, * (char**) controlDesc[i].ptr ?
                                         * (char**) controlDesc[i].ptr : ""); j++;
        } else {
-           sprintf(def, "%d", * (int*) controlDesc[i].ptr);
+         snprintf(def, MSG_SIZ,  "%d", * (int*) controlDesc[i].ptr);
            XtSetArg(args[j], XtNstring, def); j++;
        }
        XtSetArg(args[j], XtNfromHoriz, upperLeft); j++;
@@ -1310,7 +1310,7 @@ void UciPopUp()
     XtSetArg(args[j], XtNleft, XtChainRight);  j++;
     XtSetArg(args[j], XtNright, XtChainRight);  j++;
     XtSetArg(args[j], XtNstate, appData.ponderNextMove);  j++;
-    w4 = XtCreateManagedWidget(_("Ponder"), toggleWidgetClass, form, args, j);   
+    w4 = XtCreateManagedWidget(_("Ponder"), toggleWidgetClass, form, args, j);
 
     j=0;
     XtSetArg(args[j], XtNfromVert, last);  j++;
@@ -1318,41 +1318,41 @@ void UciPopUp()
     XtSetArg(args[j], XtNtop, XtChainBottom);  j++;
     XtSetArg(args[j], XtNleft, XtChainLeft);  j++;
     XtSetArg(args[j], XtNright, XtChainLeft);  j++;
-    b_ok = XtCreateManagedWidget(_("OK"), commandWidgetClass, form, args, j);   
+    b_ok = XtCreateManagedWidget(_("OK"), commandWidgetClass, form, args, j);
     XtAddCallback(b_ok, XtNcallback, UciCallback, (XtPointer) 0);
 
     XtSetArg(args[j], XtNfromHoriz, b_ok);  j++;
-    b_cancel = XtCreateManagedWidget(_("cancel"), commandWidgetClass, form, args, j);   
+    b_cancel = XtCreateManagedWidget(_("cancel"), commandWidgetClass, form, args, j);
     XtAddCallback(b_cancel, XtNcallback, UciPopDown, (XtPointer) 0);
 
     j = 5;
     XtSetArg(args[j], XtNfromHoriz, upperLeft);  j++;
     XtSetArg(args[j], XtNstate, appData.usePolyglotBook);  j++;
-    w1 = XtCreateManagedWidget(_(" use book "), toggleWidgetClass, form, args, j);   
+    w1 = XtCreateManagedWidget(_(" use book "), toggleWidgetClass, form, args, j);
 //    XtAddCallback(w1, XtNcallback, UciCallback, (XtPointer) 0);
 
     j = 5;
     XtSetArg(args[j], XtNfromHoriz, w1);  j++;
     XtSetArg(args[j], XtNstate, appData.firstHasOwnBookUCI);  j++;
-    w2 = XtCreateManagedWidget(_("own book 1"), toggleWidgetClass, form, args, j);   
+    w2 = XtCreateManagedWidget(_("own book 1"), toggleWidgetClass, form, args, j);
 //    XtAddCallback(w2, XtNcallback, UciCallback, (XtPointer) 0);
 
     j = 5;
     XtSetArg(args[j], XtNfromHoriz, w2);  j++;
     XtSetArg(args[j], XtNstate, appData.secondHasOwnBookUCI);  j++;
-    w3 = XtCreateManagedWidget(_("own book 2"), toggleWidgetClass, form, args, j);   
+    w3 = XtCreateManagedWidget(_("own book 2"), toggleWidgetClass, form, args, j);
 //    XtAddCallback(w3, XtNcallback, UciCallback, (XtPointer) 0);
 
     XtRealizeWidget(popup);
     CatchDeleteWindow(popup, "UciPopDown");
-    
+
     XQueryPointer(xDisplay, xBoardWindow, &root, &child,
                  &x, &y, &win_x, &win_y, &mask);
-    
+
     XtSetArg(args[0], XtNx, x - 10);
     XtSetArg(args[1], XtNy, y - 30);
     XtSetValues(popup, args, 2);
-    
+
     XtPopup(popup, XtGrabExclusive);
     UciUp = True;
 
@@ -1397,10 +1397,10 @@ void SpinCallback(w, client_data, call_data)
     char buf[MSG_SIZ];
     int i, j;
     int data = (intptr_t) client_data;
-    
+
     XtSetArg(args[0], XtNlabel, &name);
     XtGetValues(w, args, 1);
-    
+
     j = 0;
     XtSetArg(args[0], XtNstring, &val);
     XtGetValues(currentCps->option[data].handle, args, 1);
@@ -1411,7 +1411,7 @@ void SpinCallback(w, client_data, call_data)
     if (strcmp(name, "-") == 0) {
        if(--j < currentCps->option[data].min) return;
     } else return;
-    sprintf(buf, "%d", j);
+    snprintf(buf, MSG_SIZ,  "%d", j);
     XtSetArg(args[0], XtNstring, buf);
     XtSetValues(currentCps->option[data].handle, args, 1);
 }
@@ -1426,10 +1426,10 @@ void SettingsCallback(w, client_data, call_data)
     char buf[MSG_SIZ];
     int i, j;
     int data = (intptr_t) client_data;
-    
+
     XtSetArg(args[0], XtNlabel, &name);
     XtGetValues(w, args, 1);
-    
+
     if (strcmp(name, _("cancel")) == 0) {
         SettingsPopDown();
         return;
@@ -1444,7 +1444,7 @@ void SettingsCallback(w, client_data, call_data)
                    XtGetValues(currentCps->option[i].handle, args, 1);
                    if(strcmp(currentCps->option[i].textValue, val)) {
                      safeStrCpy(currentCps->option[i].textValue, val, sizeof(currentCps->option[i].textValue)/sizeof(currentCps->option[i].textValue[0]));
-                     sprintf(buf, "option %s=%s\n", currentCps->option[i].name, val);
+                     snprintf(buf, MSG_SIZ,  "option %s=%s\n", currentCps->option[i].name, val);
                      SendToProgram(buf, currentCps);
                    }
                    break;
@@ -1456,7 +1456,7 @@ void SettingsCallback(w, client_data, call_data)
                    if(j < currentCps->option[i].min) j = currentCps->option[i].min;
                    if(currentCps->option[i].value != j) {
                        currentCps->option[i].value = j;
-                       sprintf(buf, "option %s=%d\n", currentCps->option[i].name, j);
+                       snprintf(buf, MSG_SIZ,  "option %s=%d\n", currentCps->option[i].name, j);
                        SendToProgram(buf, currentCps);
                    }
                    break;
@@ -1466,14 +1466,14 @@ void SettingsCallback(w, client_data, call_data)
                    XtGetValues(currentCps->option[i].handle, args, 1);
                    if(currentCps->option[i].value != j) {
                        currentCps->option[i].value = j;
-                       sprintf(buf, "option %s=%d\n", currentCps->option[i].name, j);
+                       snprintf(buf, MSG_SIZ,  "option %s=%d\n", currentCps->option[i].name, j);
                        SendToProgram(buf, currentCps);
                    }
                    break;
                case ComboBox:
                    if(currentCps->option[i].value != values[i]) {
                        currentCps->option[i].value = values[i];
-                       sprintf(buf, "option %s=%s\n", currentCps->option[i].name, 
+                       snprintf(buf, MSG_SIZ,  "option %s=%s\n", currentCps->option[i].name,
                                ((char**)currentCps->option[i].textValue)[values[i]]);
                        SendToProgram(buf, currentCps);
                    }
@@ -1481,13 +1481,13 @@ void SettingsCallback(w, client_data, call_data)
            }
        }
        if(data) { // send save-button command to engine
-           sprintf(buf, "option %s\n", name);
-           SendToProgram(buf, currentCps);
+         snprintf(buf, MSG_SIZ,  "option %s\n", name);
+         SendToProgram(buf, currentCps);
        }
         SettingsPopDown();
         return;
     }
-    sprintf(buf, "option %s\n", name);
+    snprintf(buf, MSG_SIZ,  "option %s\n", name);
     SendToProgram(buf, currentCps);
 }
 
@@ -1528,7 +1528,7 @@ void CreateComboPopup(parent, name, n, mb)
                          (caddr_t)(intptr_t) (256*n+i));
        i++;
     }
-}      
+}
 
 void SettingsPopUp(ChessProgramState *cps)
 {
@@ -1538,7 +1538,7 @@ void SettingsPopUp(ChessProgramState *cps)
     int x, y, i, j, height, width, h, c;
     int win_x, win_y, maxWidth, maxTextWidth;
     unsigned int mask;
-    char def[80], *p, *q;
+    char def[MSG_SIZ], *p, *q;
     static char pane[6] = "paneX";
     Widget texts[100], forelast = NULL, anchor, widest;
 
@@ -1553,7 +1553,7 @@ void SettingsPopUp(ChessProgramState *cps)
     SettingsShell = popup =
       XtCreatePopupShell(_("Settings Menu"), transientShellWidgetClass,
                         shellWidget, args, i);
-    
+
     layout =
       XtCreateManagedWidget(layoutName, formWidgetClass, popup,
                            layoutArgs, XtNumber(layoutArgs));
@@ -1566,7 +1566,7 @@ void SettingsPopUp(ChessProgramState *cps)
     XtSetArg(args[j], XtNfromHoriz, leftMargin);  j++;
     XtSetValues(form, args, j);
     leftMargin = form;
+
     last = widest = NULL; anchor = forelast;
     for(h=0; h<height; h++) {
        forelast = last;
@@ -1574,14 +1574,14 @@ void SettingsPopUp(ChessProgramState *cps)
         if(i >= cps->nrOptions) break;
        switch(cps->option[i].type) {
          case Spin:
-           sprintf(def, "%d", cps->option[i].value);
+           snprintf(def, MSG_SIZ,  "%d", cps->option[i].value);
          case TextBox:
            j=0;
            XtSetArg(args[j], XtNfromVert, last);  j++;
            XtSetArg(args[j], XtNborderWidth, 0);  j++;
            XtSetArg(args[j], XtNjustify, XtJustifyLeft);  j++;
            texts[h] =
-           dialog = XtCreateManagedWidget(cps->option[i].name, labelWidgetClass, form, args, j);   
+           dialog = XtCreateManagedWidget(cps->option[i].name, labelWidgetClass, form, args, j);
            j=0;
            XtSetArg(args[j], XtNfromVert, last);  j++;
            XtSetArg(args[j], XtNfromHoriz, dialog);  j++;
@@ -1596,7 +1596,7 @@ void SettingsPopUp(ChessProgramState *cps)
            XtSetArg(args[j], XtNinsertPosition, 9999);  j++;
            edit = last;
            cps->option[i].handle = (void*)
-               (textField = last = XtCreateManagedWidget("text", asciiTextWidgetClass, form, args, j));   
+               (textField = last = XtCreateManagedWidget("text", asciiTextWidgetClass, form, args, j));
            XtAddEventHandler(last, ButtonPressMask, False, SetFocus, (XtPointer) popup);
            if(cps->option[i].type == TextBox) break;
 
@@ -1625,8 +1625,8 @@ void SettingsPopUp(ChessProgramState *cps)
            XtSetArg(args[j], XtNwidth, 10);  j++;
            XtSetArg(args[j], XtNheight, 10);  j++;
            XtSetArg(args[j], XtNstate, cps->option[i].value);  j++;
-           cps->option[i].handle = (void*) 
-               (dialog = XtCreateManagedWidget(" ", toggleWidgetClass, form, args, j));   
+           cps->option[i].handle = (void*)
+               (dialog = XtCreateManagedWidget(" ", toggleWidgetClass, form, args, j));
            j=0;
            XtSetArg(args[j], XtNfromVert, last);  j++;
            XtSetArg(args[j], XtNfromHoriz, dialog);  j++;
@@ -1639,8 +1639,8 @@ void SettingsPopUp(ChessProgramState *cps)
            j=0;
            XtSetArg(args[j], XtNfromVert, last);  j++;
            XtSetArg(args[j], XtNstate, cps->option[i].value);  j++;
-           cps->option[i].handle = (void*) 
-               (dialog = last = XtCreateManagedWidget(cps->option[i].name, commandWidgetClass, form, args, j));   
+           cps->option[i].handle = (void*)
+               (dialog = last = XtCreateManagedWidget(cps->option[i].name, commandWidgetClass, form, args, j));
            XtAddCallback(last, XtNcallback, SettingsCallback,
                          (XtPointer)(intptr_t) (cps->option[i].type == SaveButton));
            break;
@@ -1657,8 +1657,8 @@ void SettingsPopUp(ChessProgramState *cps)
            XtSetArg(args[j], XtNwidth, 100);  j++;
            XtSetArg(args[j], XtNmenuName, XtNewString(cps->option[i].name));  j++;
            XtSetArg(args[j], XtNlabel, ((char**)cps->option[i].textValue)[cps->option[i].value]);  j++;
-           cps->option[i].handle = (void*) 
-               (last = XtCreateManagedWidget(" ", menuButtonWidgetClass, form, args, j));   
+           cps->option[i].handle = (void*)
+               (last = XtCreateManagedWidget(" ", menuButtonWidgetClass, form, args, j));
            CreateComboPopup(last, cps->option[i].name, i, (char **) cps->option[i].textValue);
            values[i] = cps->option[i].value;
            break;
@@ -1708,23 +1708,23 @@ void SettingsPopUp(ChessProgramState *cps)
     XtSetArg(args[j], XtNleft, XtChainRight);  j++;
     XtSetArg(args[j], XtNright, XtChainRight);  j++;
     XtSetArg(args[j], XtNfromHoriz, widest ? widest : dialog);  j++;
-    b_ok = XtCreateManagedWidget(_("OK"), commandWidgetClass, form, args, j);   
+    b_ok = XtCreateManagedWidget(_("OK"), commandWidgetClass, form, args, j);
     XtAddCallback(b_ok, XtNcallback, SettingsCallback, (XtPointer) 0);
 
     XtSetArg(args[j-1], XtNfromHoriz, b_ok);
-    b_cancel = XtCreateManagedWidget(_("cancel"), commandWidgetClass, form, args, j);   
+    b_cancel = XtCreateManagedWidget(_("cancel"), commandWidgetClass, form, args, j);
     XtAddCallback(b_cancel, XtNcallback, SettingsPopDown, (XtPointer) 0);
 
     XtRealizeWidget(popup);
     CatchDeleteWindow(popup, "SettingsPopDown");
-    
+
     XQueryPointer(xDisplay, xBoardWindow, &root, &child,
                  &x, &y, &win_x, &win_y, &mask);
-    
+
     XtSetArg(args[0], XtNx, x - 10);
     XtSetArg(args[1], XtNy, y - 30);
     XtSetValues(popup, args, 2);
-    
+
     XtPopup(popup, XtGrabExclusive);
     SettingsUp = True;
 
index d309e83..c2cda05 100644 (file)
--- a/zic2xpm.c
+++ b/zic2xpm.c
@@ -115,6 +115,7 @@ typedef struct {
 } z2xpm;
 
 #define NR_ZIICS_COLORS 4
+#define BUFLEN 100
 
 /* SHOWSETS.PAS (from ZIICS) states that images may only
    use color numbers 0, 2, 14, and 15 */
@@ -441,7 +442,7 @@ int process_file_xim( filename )
   int nr_pieces = 6;
   int nr_kinds = 4;
   FILE *fp;
-  char buf[100];
+  char buf[BUFLEN];
 
   src_name = filename;
   
@@ -478,18 +479,18 @@ int process_file_xim( filename )
                {
                  printf( "." );
                  /* Form output filename -- <piece><kind><size>.xim */
-                 sprintf(buf, "%c%s%d.xim", pieces[piece], prefixes[kind], w);
+                 snprintf(buf, BUFLEN, "%c%s%d.xim", pieces[piece], prefixes[kind], w);
                  create_piece_xim( buf, fp, w, h );
                }
          printf("\n");
        }
 
   /* Write the light & dark squares */
-  sprintf( buf, "lsq%d.xim", w );
+  snprintf( buf, BUFLEN, "lsq%d.xim", w );
   printf("Light Square" );
   create_piece_xim( buf, fp, w, h );
 
-  sprintf( buf, "dsq%d.xim", w );
+  snprintf( buf, BUFLEN, "dsq%d.xim", w );
   printf("\nDark Square" );
   create_piece_xim( buf, fp, w, h );  
   printf("\n");
@@ -508,7 +509,7 @@ int process_file_xpm( filename )
   int nr_pieces = 6;
   int nr_kinds = 4;
   FILE *fp;
-  char buf[100];
+  char buf[BUFLEN];
 
   src_name = filename;
   
@@ -545,18 +546,18 @@ int process_file_xpm( filename )
                {
                  printf( "." );
                  /* Form output filename -- <piece><kind><size>.xpm */
-                 sprintf(buf, "%c%s%d.xpm", pieces[piece], prefixes[kind], w);
+                 snprintf(buf, BUFLEN, "%c%s%d.xpm", pieces[piece], prefixes[kind], w);
                  create_piece_xpm( buf, fp, w, h );
                }
          printf("\n");
        }
 
   /* Write the light & dark squares */
-  sprintf( buf, "lsq%d.xpm", w );
+  snprintf( buf, BUFLEN, "lsq%d.xpm", w );
   printf("Light Square" );
   create_piece_xpm( buf, fp, w, h );
 
-  sprintf( buf, "dsq%d.xpm", w );
+  snprintf( buf, BUFLEN, "dsq%d.xpm", w );
   printf("\nDark Square" );
   create_piece_xpm( buf, fp, w, h );  
   printf("\n");
diff --git a/zippy.c b/zippy.c
index 849bdb1..9fdedc5 100644 (file)
--- a/zippy.c
+++ b/zippy.c
@@ -422,7 +422,7 @@ int ZippyControl(buf, i)
            (gameMode == IcsPlayingBlack &&
             StrCaseCmp(player, gameInfo.white) == 0)) {
 
-         sprintf(reply, "%ssay This computer does not play Crafty clones\n%sabort\n%s+noplay %s\n",
+         snprintf(reply, MSG_SIZ, "%ssay This computer does not play Crafty clones\n%sabort\n%s+noplay %s\n",
                  ics_prefix, ics_prefix, ics_prefix, player);
          SendToICS(reply);
        }
@@ -452,17 +452,17 @@ int ZippyControl(buf, i)
         looking_at(buf, i, "* tells you: [automatic message] I chose you"))) {
        player = StripHighlightAndTitle(star_match[0]);
        if (appData.zippyBughouse > 1 && first.initDone) {
-           sprintf(reply, "%spartner %s\n", ics_prefix, player);
+           snprintf(reply, MSG_SIZ,"%spartner %s\n", ics_prefix, player);
            SendToICS(reply);
            if (strcmp(zippyPartner, player) != 0) {
              safeStrCpy(zippyPartner, player, sizeof(zippyPartner)/sizeof(zippyPartner[0]));
              SendToProgram(reply + strlen(ics_prefix), &first);
            }
        } else if (appData.zippyBughouse > 0) {
-           sprintf(reply, "%sdecline %s\n", ics_prefix, player);
+           snprintf(reply, MSG_SIZ, "%sdecline %s\n", ics_prefix, player);
            SendToICS(reply);
        } else {
-           sprintf(reply, "%stell %s This computer cannot play bughouse\n",
+         snprintf(reply, MSG_SIZ, "%stell %s This computer cannot play bughouse\n",
                    ics_prefix, player);
            SendToICS(reply);
        }
@@ -472,7 +472,7 @@ int ZippyControl(buf, i)
     if (appData.zippyPlay && appData.zippyBughouse && first.initDone &&
        looking_at(buf, i, "* agrees to be your partner")) {
        player = StripHighlightAndTitle(star_match[0]);
-       sprintf(reply, "partner %s\n", player);
+       snprintf(reply, MSG_SIZ, "partner %s\n", player);
        if (strcmp(zippyPartner, player) != 0) {
          safeStrCpy(zippyPartner, player, sizeof(zippyPartner)/sizeof(zippyPartner[0]));
          SendToProgram(reply, &first);
@@ -507,10 +507,10 @@ int ZippyControl(buf, i)
        player = StripHighlightAndTitle(star_match[0]);
        if (strcmp(zippyPartner, player) != 0) {
          safeStrCpy(zippyPartner, player, sizeof(zippyPartner)/sizeof(zippyPartner[0]));
-         sprintf(reply, "partner %s\n", player);
+         snprintf(reply, MSG_SIZ, "partner %s\n", player);
          SendToProgram(reply, &first);
        }
-       sprintf(reply, "ptell %s\n", star_match[1]);
+       snprintf(reply, MSG_SIZ, "ptell %s\n", star_match[1]);
        SendToProgram(reply, &first);
        return TRUE;
     }
@@ -538,7 +538,7 @@ int ZippyControl(buf, i)
                    strlen(appData.zippyWrongPassword)) == 0) {
            p = star_match[1] + strlen(appData.zippyWrongPassword);
            while (*p == ' ') p++;
-           sprintf(reply, "wrong %s\n", player);
+           snprintf(reply, MSG_SIZ, "wrong %s\n", player);
            SendToICS(reply);
        } else if (appData.zippyBughouse && first.initDone &&
                   strcmp(player, zippyPartner) == 0) {
@@ -547,12 +547,12 @@ int ZippyControl(buf, i)
            SendToProgram("\n", &first);
        } else if (strncmp(star_match[1], HI, 6) == 0) {
            extern char* programVersion;
-           sprintf(reply, "%stell %s %s\n",
+           snprintf(reply, MSG_SIZ, "%stell %s %s\n",
                    ics_prefix, player, programVersion);
            SendToICS(reply);
        } else if (strncmp(star_match[1], "W0W!! ", 6) == 0) {
            extern char* programVersion;
-           sprintf(reply, "%stell %s %s\n", ics_prefix,
+           snprintf(reply, MSG_SIZ, "%stell %s %s\n", ics_prefix,
                    player, programVersion);
            SendToICS(reply);
        } else if (appData.zippyTalk && (((unsigned) random() % 10) < 9)) {
@@ -573,7 +573,7 @@ int ZippyControl(buf, i)
 
     if (looking_at(buf, i, "* spoofs you:")) {
         player = StripHighlightAndTitle(star_match[0]);
-        sprintf(reply, "spoofedby %s\n", player);
+        snprintf(reply, MSG_SIZ, "spoofedby %s\n", player);
         SendToICS(reply);
     }
 
@@ -598,7 +598,7 @@ int ZippyConverse(buf, i)
            return TRUE;
        } else if (appData.zippyPinhead[0] != NULLCHAR &&
                   StrCaseStr(star_match[1], appData.zippyPinhead) != NULL) {
-           sprintf(reply, "insult %s\n", player);
+         snprintf(reply, MSG_SIZ, "insult %s\n", player);
            SendToICS(reply);
        } else if (ZippyCalled(star_match[1])) {
            Speak("shout", NULL);
@@ -693,7 +693,7 @@ int ZippyConverse(buf, i)
         atoi(star_match[0]) != 0) ||
        looking_at(buf, i, "* has left a message for you") ||
        looking_at(buf, i, "* just sent you a message")) {
-        sprintf(reply, "%smessages\n%sclearmessages *\n",
+      snprintf(reply, MSG_SIZ, "%smessages\n%sclearmessages *\n",
                ics_prefix, ics_prefix);
        SendToICS(reply);
        return TRUE;
@@ -703,7 +703,7 @@ int ZippyConverse(buf, i)
        if (((unsigned) random() % 3) == 0) {
            char *player = StripHighlightAndTitle(star_match[0]);
            safeStrCpy(lastgreet, player, sizeof(lastgreet)/sizeof(lastgreet[0]));
-           sprintf(reply, "greet %s\n", player);
+           snprintf(reply, MSG_SIZ, "greet %s\n", player);
            SendToICS(reply);
            Speak("tell", player);
        }
@@ -712,7 +712,7 @@ int ZippyConverse(buf, i)
     if (looking_at(buf, i, "Notification: * has departed")) {
        if (((unsigned) random() % 3) == 0) {
            char *player = StripHighlightAndTitle(star_match[0]);
-           sprintf(reply, "farewell %s\n", player);
+           snprintf(reply, MSG_SIZ, "farewell %s\n", player);
            SendToICS(reply);
        }
     }
@@ -720,7 +720,7 @@ int ZippyConverse(buf, i)
     if (looking_at(buf, i, "Not sent -- * is censoring you")) {
        char *player = StripHighlightAndTitle(star_match[0]);
        if (strcmp(player, lastgreet) == 0) {
-           sprintf(reply, "%s-notify %s\n", ics_prefix, player);
+         snprintf(reply, MSG_SIZ, "%s-notify %s\n", ics_prefix, player);
            SendToICS(reply);
        }
     }
@@ -793,7 +793,7 @@ void ZippyHandleChallenge(srated, swild, sbase, sincrement, opponent)
        easier to use the ICS formula feature instead. */
 
     if (variant == VariantLoadable) {
-        sprintf(buf,
+      snprintf(buf, MSG_SIZ,
         "%stell %s This computer can't play wild type %s\n%sdecline %s\n",
                ics_prefix, opponent, swild, ics_prefix, opponent);
        SendToICS(buf);
@@ -802,7 +802,7 @@ void ZippyHandleChallenge(srated, swild, sbase, sincrement, opponent)
     if (StrStr(appData.zippyVariants, varname) == NULL ||
               ((i=first.protocolVersion) != 1 && StrStr(first.variants, varname) == NULL) /* [HGM] zippyvar */
                                                           ) {
-        sprintf(buf,
+      snprintf(buf, MSG_SIZ,
         "%stell %s This computer can't play %s [%s], only %s\n%sdecline %s\n",
                ics_prefix, opponent, swild, varname,
                 i ? first.variants : appData.zippyVariants,                               /* [HGM] zippyvar */
@@ -824,7 +824,7 @@ void ZippyHandleChallenge(srated, swild, sbase, sincrement, opponent)
        strcmp(opponent, zippyLastOpp) == 0 &&
        zippyConsecGames >= appData.zippyMaxGames &&
        difftime(time(0), zippyLastGameEnd) < appData.zippyReplayTimeout) {
-      sprintf(buf, "%stell %s Sorry, you have just played %d consecutive games against %s.  To give others a chance, please wait %d seconds or until someone else has played.\n%sdecline %s\n",
+      snprintf(buf, MSG_SIZ,  "%stell %s Sorry, you have just played %d consecutive games against %s.  To give others a chance, please wait %d seconds or until someone else has played.\n%sdecline %s\n",
              ics_prefix, opponent, zippyConsecGames, ics_handle,
              appData.zippyReplayTimeout, ics_prefix, opponent);
       SendToICS(buf);
@@ -834,7 +834,7 @@ void ZippyHandleChallenge(srated, swild, sbase, sincrement, opponent)
     /* [HGM] aborter: opponent is cheater that aborts games he doesn't like on first move. Make him wait */
     if (strcmp(opponent, zippyOffender) == 0 &&
        difftime(time(0), zippyLastGameEnd) < appData.zippyReplayTimeout) {
-      sprintf(buf, "%stell %s Sorry, your previous game against %s was rather short. "
+      snprintf(buf, MSG_SIZ,  "%stell %s Sorry, your previous game against %s was rather short. "
                   " It will wait %d seconds to see if a tougher opponent comes along.\n%sdecline %s\n",
              ics_prefix, opponent, ics_handle,
              appData.zippyReplayTimeout, ics_prefix, opponent);
@@ -844,13 +844,13 @@ void ZippyHandleChallenge(srated, swild, sbase, sincrement, opponent)
 
     /* Engine not yet initialized or still thinking about last game? */
     if (!first.initDone || first.lastPing != first.lastPong) {
-      sprintf(buf, "%stell %s I'm not quite ready for a new game yet; try again soon.\n%sdecline %s\n",
+      snprintf(buf, MSG_SIZ,  "%stell %s I'm not quite ready for a new game yet; try again soon.\n%sdecline %s\n",
              ics_prefix, opponent, ics_prefix, opponent);
       SendToICS(buf);
       return;
     }
 
-    sprintf(buf, "%saccept %s\n", ics_prefix, opponent);
+    snprintf(buf, MSG_SIZ, "%saccept %s\n", ics_prefix, opponent);
     SendToICS(buf);
     if (appData.zippyTalk) {
       Speak("tell", opponent);
@@ -999,7 +999,7 @@ void ZippyFirstBoard(moveNum, basetime, increment)
 
     /* Send the variant command if needed */
     if (gameInfo.variant != VariantNormal) {
-      sprintf(buf, "variant %s\n", VariantName(gameInfo.variant));
+      snprintf(buf, MSG_SIZ,  "variant %s\n", VariantName(gameInfo.variant));
       SendToProgram(buf, &first);
     }
 
@@ -1010,7 +1010,7 @@ void ZippyFirstBoard(moveNum, basetime, increment)
       sentPos = TRUE;
     }
 
-    sprintf(buf, "level 0 %d %d\n", basetime, increment);
+    snprintf(buf, MSG_SIZ,  "level 0 %d %d\n", basetime, increment);
     SendToProgram(buf, &first);
 
     /* Count consecutive games from one opponent */
@@ -1038,11 +1038,11 @@ void ZippyFirstBoard(moveNum, basetime, increment)
     firstMove = FALSE;
     if (gameMode == IcsPlayingWhite) {
         if (first.sendName) {
-         sprintf(buf, "name %s\n", gameInfo.black);
+         snprintf(buf, MSG_SIZ,  "name %s\n", gameInfo.black);
          SendToProgram(buf, &first);
        }
        safeStrCpy(ics_handle, gameInfo.white, MSG_SIZ);
-       sprintf(buf, "rating %d %d\n", w, b);
+       snprintf(buf, MSG_SIZ,  "rating %d %d\n", w, b);
        SendToProgram(buf, &first);
        if (sentPos) {
            /* Position sent above, engine is in force mode */
@@ -1089,11 +1089,11 @@ void ZippyFirstBoard(moveNum, basetime, increment)
        }
     } else if (gameMode == IcsPlayingBlack) {
         if (first.sendName) {
-         sprintf(buf, "name %s\n", gameInfo.white);
+         snprintf(buf, MSG_SIZ,  "name %s\n", gameInfo.white);
          SendToProgram(buf, &first);
        }
        safeStrCpy(ics_handle, gameInfo.black, MSG_SIZ);
-       sprintf(buf, "rating %d %d\n", b, w);
+       snprintf(buf, MSG_SIZ,  "rating %d %d\n", b, w);
        SendToProgram(buf, &first);
        if (sentPos) {
            /* Position sent above, engine is in force mode */
@@ -1148,7 +1148,7 @@ ZippyHoldings(white_holding, black_holding, new_piece)
 {
     char buf[MSG_SIZ];
     if (gameMode != IcsPlayingBlack && gameMode != IcsPlayingWhite) return;
-    sprintf(buf, "holding [%s] [%s] %s\n",
+    snprintf(buf, MSG_SIZ,  "holding [%s] [%s] %s\n",
            white_holding, black_holding, new_piece);
     SendToProgram(buf, &first);
 }