Merge branch 'warnings' of https://github.com/CendioOssman/tigervnc
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 5ecd89e..407bf67 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -67,6 +67,18 @@
 set(CMAKE_C_FLAGS_MINSIZEREL "${CMAKE_C_FLAGS_MINSIZEREL} -UNDEBUG")
 set(CMAKE_CXX_FLAGS_MINSIZEREL "${CMAKE_CXX_FLAGS_MINSIZEREL} -UNDEBUG")
 
+# Tell the compiler to be stringent
+set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wall -Wformat=2")
+set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -Wformat=2")
+# Make sure we catch these issues whilst developing
+IF(CMAKE_BUILD_TYPE MATCHES Debug)
+  set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Werror")
+  set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Werror")
+  # We have a lot of old GnuTLS crud we need to ignore for now
+  set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wno-error=deprecated-declarations")
+  set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-error=deprecated-declarations")
+ENDIF()
+
 if(NOT DEFINED BUILD_WINVNC)
   set(BUILD_WINVNC 1)
 endif()
diff --git a/common/network/TcpSocket.cxx b/common/network/TcpSocket.cxx
index 2545034..e19f52b 100644
--- a/common/network/TcpSocket.cxx
+++ b/common/network/TcpSocket.cxx
@@ -155,6 +155,10 @@
 		    gai_strerror(result));
   }
 
+  // This logic is too complex for the compiler to determine if
+  // sock is properly assigned or not.
+  sock = -1;
+
   for (current = ai; current != NULL; current = current->ai_next) {
     family = current->ai_family;
 
@@ -230,6 +234,9 @@
   }
 
   freeaddrinfo(ai);
+
+  if (current == NULL)
+    throw Exception("No useful address for host");
 #endif /* HAVE_GETADDRINFO */
 
   if (result == -1)
@@ -591,7 +598,6 @@
 
 void TcpListener::getMyAddresses(std::list<char*>* result) {
 #if defined(HAVE_GETADDRINFO) && defined(HAVE_INET_PTON)
-  vnc_sockaddr_t sa;
   struct addrinfo *ai, *current, hints;
 
   memset(&hints, 0, sizeof(struct addrinfo));
diff --git a/common/rdr/Exception.h b/common/rdr/Exception.h
index ea10f9d..62f452b 100644
--- a/common/rdr/Exception.h
+++ b/common/rdr/Exception.h
@@ -21,12 +21,18 @@
 #ifndef __RDR_EXCEPTION_H__
 #define __RDR_EXCEPTION_H__
 
+#ifdef __GNUC__
+#  define __printf_attr(a, b) __attribute__((__format__ (__printf__, a, b)))
+#else
+#  define __printf_attr(a, b)
+#endif // __GNUC__
+
 namespace rdr {
 
   struct Exception {
     enum { len = 256 };
     char str_[len];
-    Exception(const char *format = 0, ...);
+    Exception(const char *format = 0, ...) __printf_attr(2, 3);
     virtual ~Exception() {}
     virtual const char* str() const { return str_; }
   };
@@ -37,15 +43,15 @@
   }; 
 
   struct TimedOut : public Exception {
-    TimedOut(const char* s="Timed out") : Exception(s) {}
+    TimedOut(const char* s="Timed out") : Exception("%s", s) {}
   };
  
   struct EndOfStream : public Exception {
-    EndOfStream(const char* s="End of stream") : Exception(s) {}
+    EndOfStream(const char* s="End of stream") : Exception("%s", s) {}
   };
 
   struct FrameException : public Exception {
-    FrameException(const char* s="Frame exception") : Exception(s) {}
+    FrameException(const char* s="Frame exception") : Exception("%s", s) {}
   };
 
 }
diff --git a/common/rdr/FileInStream.cxx b/common/rdr/FileInStream.cxx
index 18a9169..8d5c22e 100644
--- a/common/rdr/FileInStream.cxx
+++ b/common/rdr/FileInStream.cxx
@@ -58,7 +58,7 @@
 
 int FileInStream::overrun(int itemSize, int nItems, bool wait)
 {
-  if (itemSize > sizeof(b))
+  if (itemSize > (int)sizeof(b))
     throw Exception("FileInStream overrun: max itemSize exceeded");
 
   if (end - ptr != 0)
@@ -72,7 +72,7 @@
     size_t n = fread((U8 *)end, b + sizeof(b) - end, 1, file);
     if (n < 1) {
       if (n < 0 || ferror(file))
-        throw Exception(strerror(errno));
+        throw SystemException("fread", errno);
       if (feof(file))
         throw EndOfStream();
       if (n == 0) { return 0; }
diff --git a/common/rdr/RandomStream.cxx b/common/rdr/RandomStream.cxx
index 7056c2c..3fde18d 100644
--- a/common/rdr/RandomStream.cxx
+++ b/common/rdr/RandomStream.cxx
@@ -44,7 +44,7 @@
 #ifdef RFB_HAVE_WINCRYPT
   provider = 0;
   if (!CryptAcquireContext(&provider, 0, 0, PROV_RSA_FULL, 0)) {
-    if (GetLastError() == NTE_BAD_KEYSET) {
+    if (GetLastError() == (DWORD)NTE_BAD_KEYSET) {
       if (!CryptAcquireContext(&provider, 0, 0, PROV_RSA_FULL, CRYPT_NEWKEYSET)) {
         fprintf(stderr, "RandomStream: unable to create keyset\n");
         provider = 0;
diff --git a/common/rdr/TLSException.cxx b/common/rdr/TLSException.cxx
index 3d39d79..bf8e97a 100644
--- a/common/rdr/TLSException.cxx
+++ b/common/rdr/TLSException.cxx
@@ -34,15 +34,8 @@
 
 #ifdef HAVE_GNUTLS
 TLSException::TLSException(const char* s, int err_)
-  : Exception(s), err(err_)
+  : Exception("%s: %s (%d)", s, gnutls_strerror(err), err), err(err_)
 {
-  strncat(str_, ": ", len-1-strlen(str_));
-  strncat(str_, gnutls_strerror(err), len-1-strlen(str_));
-  strncat(str_, " (", len-1-strlen(str_));
-  char buf[20];
-  sprintf(buf,"%d",err);
-  strncat(str_, buf, len-1-strlen(str_));
-  strncat(str_, ")", len-1-strlen(str_));
 }
 #endif /* HAVE_GNUTLS */
 
diff --git a/common/rdr/TLSInStream.cxx b/common/rdr/TLSInStream.cxx
index 4d2c9ec..21b6056 100644
--- a/common/rdr/TLSInStream.cxx
+++ b/common/rdr/TLSInStream.cxx
@@ -44,7 +44,7 @@
       return -1;
     }
 
-    if (in->getend() - in->getptr() < size)
+    if (in->getend() - in->getptr() < (ptrdiff_t)size)
       size = in->getend() - in->getptr();
   
     in->readBytes(data, size);
diff --git a/common/rfb/CConnection.cxx b/common/rfb/CConnection.cxx
index e0a23b5..8ccd948 100644
--- a/common/rfb/CConnection.cxx
+++ b/common/rfb/CConnection.cxx
@@ -97,12 +97,11 @@
 
   // The only official RFB protocol versions are currently 3.3, 3.7 and 3.8
   if (cp.beforeVersion(3,3)) {
-    char msg[256];
-    sprintf(msg,"Server gave unsupported RFB protocol version %d.%d",
-            cp.majorVersion, cp.minorVersion);
-    vlog.error("%s", msg);
+    vlog.error("Server gave unsupported RFB protocol version %d.%d",
+               cp.majorVersion, cp.minorVersion);
     state_ = RFBSTATE_INVALID;
-    throw Exception(msg);
+    throw Exception("Server gave unsupported RFB protocol version %d.%d",
+                    cp.majorVersion, cp.minorVersion);
   } else if (useProtocol3_3 || cp.beforeVersion(3,7)) {
     cp.setVersion(3,3);
   } else if (cp.afterVersion(3,8)) {
diff --git a/common/rfb/CMsgHandler.cxx b/common/rfb/CMsgHandler.cxx
index ce8b271..11c979a 100644
--- a/common/rfb/CMsgHandler.cxx
+++ b/common/rfb/CMsgHandler.cxx
@@ -38,13 +38,13 @@
   cp.height = height;
 }
 
-void CMsgHandler::setExtendedDesktopSize(int reason, int result,
+void CMsgHandler::setExtendedDesktopSize(unsigned reason, unsigned result,
                                          int width, int height,
                                          const ScreenSet& layout)
 {
   cp.supportsSetDesktopSize = true;
 
-  if ((reason == (signed)reasonClient) && (result != (signed)resultSuccess))
+  if ((reason == reasonClient) && (result != resultSuccess))
     return;
 
   if (!layout.validate(width, height))
diff --git a/common/rfb/CMsgHandler.h b/common/rfb/CMsgHandler.h
index 5e333d2..7d2cdc2 100644
--- a/common/rfb/CMsgHandler.h
+++ b/common/rfb/CMsgHandler.h
@@ -46,7 +46,7 @@
     // methods to set the members of cp appropriately.
 
     virtual void setDesktopSize(int w, int h);
-    virtual void setExtendedDesktopSize(int reason, int result,
+    virtual void setExtendedDesktopSize(unsigned reason, unsigned result,
                                         int w, int h,
                                         const ScreenSet& layout);
     virtual void setCursor(int width, int height, const Point& hotspot,
diff --git a/common/rfb/EncodeManager.cxx b/common/rfb/EncodeManager.cxx
index e632387..9122cd7 100644
--- a/common/rfb/EncodeManager.cxx
+++ b/common/rfb/EncodeManager.cxx
@@ -91,6 +91,8 @@
     return "Tight (JPEG)";
   case encoderZRLE:
     return "ZRLE";
+  case encoderClassMax:
+    break;
   }
 
   return "Unknown Encoder Class";
@@ -111,6 +113,8 @@
     return "Indexed RLE";
   case encoderFullColour:
     return "Full Colour";
+  case encoderTypeMax:
+    break;
   }
 
   return "Unknown Encoder Type";
@@ -152,13 +156,15 @@
 
 void EncodeManager::logStats()
 {
-  int i, j;
+  size_t i, j;
 
   unsigned rects;
   unsigned long long pixels, bytes, equivalent;
 
   double ratio;
 
+  char a[1024], b[1024];
+
   rects = 0;
   pixels = bytes = equivalent = 0;
 
@@ -186,19 +192,23 @@
 
       ratio = (double)stats[i][j].equivalent / stats[i][j].bytes;
 
-      vlog.info("    %s: %u rects, %llu pixels",
-                encoderTypeName((EncoderType)j),
-                stats[i][j].rects, stats[i][j].pixels);
-      vlog.info("    %*s  %llu bytes (%g ratio)",
-                strlen(encoderTypeName((EncoderType)j)), "",
-                stats[i][j].bytes, ratio);
+      siPrefix(stats[i][j].rects, "rects", a, sizeof(a));
+      siPrefix(stats[i][j].pixels, "pixels", b, sizeof(b));
+      vlog.info("    %s: %s, %s", encoderTypeName((EncoderType)j), a, b);
+      iecPrefix(stats[i][j].bytes, "B", a, sizeof(a));
+      vlog.info("    %*s  %s (1:%g ratio)",
+                (int)strlen(encoderTypeName((EncoderType)j)), "",
+                a, ratio);
     }
   }
 
   ratio = (double)equivalent / bytes;
 
-  vlog.info("  Total: %u rects, %llu pixels", rects, pixels);
-  vlog.info("         %llu bytes (%g ratio)", bytes, ratio);
+  siPrefix(rects, "rects", a, sizeof(a));
+  siPrefix(pixels, "pixels", b, sizeof(b));
+  vlog.info("  Total: %s, %s", a, b);
+  iecPrefix(bytes, "B", a, sizeof(a));
+  vlog.info("         %s (1:%g ratio)", a, ratio);
 }
 
 bool EncodeManager::supported(int encoding)
@@ -603,7 +613,7 @@
   Encoder *encoder;
 
   struct RectInfo info;
-  int divisor, maxColours;
+  unsigned int divisor, maxColours;
 
   bool useRLE;
   EncoderType type;
diff --git a/common/rfb/EncodeManagerBPP.cxx b/common/rfb/EncodeManagerBPP.cxx
index f58466c..0361291 100644
--- a/common/rfb/EncodeManagerBPP.cxx
+++ b/common/rfb/EncodeManagerBPP.cxx
@@ -59,9 +59,6 @@
   rdr::UBPP colour;
   int count;
 
-  rdr::UBPP c0, c1, ci = 0;
-  int i, n0, n1, ni;
-
   info->rleRuns = 0;
   info->palette.clear();
 
diff --git a/common/rfb/Encoder.cxx b/common/rfb/Encoder.cxx
index 16f7081..56b5f38 100644
--- a/common/rfb/Encoder.cxx
+++ b/common/rfb/Encoder.cxx
@@ -25,8 +25,8 @@
 
 Encoder::Encoder(SConnection *conn_, int encoding_,
                  enum EncoderFlags flags_, unsigned int maxPaletteSize_) :
-  conn(conn_), encoding(encoding_), flags(flags_),
-  maxPaletteSize(maxPaletteSize_)
+  encoding(encoding_), flags(flags_),
+  maxPaletteSize(maxPaletteSize_), conn(conn_)
 {
 }
 
diff --git a/common/rfb/Exception.h b/common/rfb/Exception.h
index 7c2cbca..5f47fcf 100644
--- a/common/rfb/Exception.h
+++ b/common/rfb/Exception.h
@@ -24,14 +24,15 @@
   typedef rdr::Exception Exception;
   struct AuthFailureException : public Exception {
     AuthFailureException(const char* s="Authentication failure")
-      : Exception(s) {}
+      : Exception("%s", s) {}
   };
   struct AuthCancelledException : public rfb::Exception {
     AuthCancelledException(const char* s="Authentication cancelled")
-      : Exception(s) {}
+      : Exception("%s", s) {}
   };
   struct ConnFailedException : public Exception {
-    ConnFailedException(const char* s="Connection failed") : Exception(s) {}
+    ConnFailedException(const char* s="Connection failed")
+      : Exception("%s", s) {}
   };
 }
 #endif
diff --git a/common/rfb/JpegCompressor.cxx b/common/rfb/JpegCompressor.cxx
index c19af34..5df0039 100644
--- a/common/rfb/JpegCompressor.cxx
+++ b/common/rfb/JpegCompressor.cxx
@@ -123,7 +123,7 @@
 
   if(setjmp(err->jmpBuffer)) {
     // this will execute if libjpeg has an error
-    throw rdr::Exception(err->lastError);
+    throw rdr::Exception("%s", err->lastError);
   }
 
   jpeg_create_compress(cinfo);
@@ -166,7 +166,7 @@
     jpeg_abort_compress(cinfo);
     if (srcBufIsTemp && srcBuf) delete[] srcBuf;
     if (rowPointer) delete[] rowPointer;
-    throw rdr::Exception(err->lastError);
+    throw rdr::Exception("%s", err->lastError);
   }
 
   cinfo->image_width = w;
diff --git a/common/rfb/JpegDecompressor.cxx b/common/rfb/JpegDecompressor.cxx
index ca1ad22..70a4276 100644
--- a/common/rfb/JpegDecompressor.cxx
+++ b/common/rfb/JpegDecompressor.cxx
@@ -116,7 +116,7 @@
 
   if(setjmp(err->jmpBuffer)) {
     // this will execute if libjpeg has an error
-    throw rdr::Exception(err->lastError);
+    throw rdr::Exception("%s", err->lastError);
   }
 
   jpeg_create_decompress(dinfo);
@@ -162,7 +162,7 @@
     jpeg_abort_decompress(dinfo);
     if (dstBufIsTemp && dstBuf) delete[] dstBuf;
     if (rowPointer) delete[] rowPointer;
-    throw rdr::Exception(err->lastError);
+    throw rdr::Exception("%s", err->lastError);
   }
 
   src->pub.next_input_byte = jpegBuf;
diff --git a/common/rfb/KeyRemapper.cxx b/common/rfb/KeyRemapper.cxx
index 05f0763..d33f0a4 100644
--- a/common/rfb/KeyRemapper.cxx
+++ b/common/rfb/KeyRemapper.cxx
@@ -50,7 +50,7 @@
       if (bidi == '<')
         mapping[to] = from;
     } else {
-      vlog.error("warning: bad mapping %.*s", nextComma-m, m);
+      vlog.error("warning: bad mapping %.*s", (int)(nextComma-m), m);
     }
     m = nextComma;
     if (nextComma[0])
diff --git a/common/rfb/Rect.h b/common/rfb/Rect.h
index 52e92b5..b5ae254 100644
--- a/common/rfb/Rect.h
+++ b/common/rfb/Rect.h
@@ -102,7 +102,7 @@
     inline bool overlaps(const Rect &r) const {
       return tl.x < r.br.x && tl.y < r.br.y && br.x > r.tl.x && br.y > r.tl.y;
     }
-    inline unsigned int area() const {return is_empty() ? 0 : (br.x-tl.x)*(br.y-tl.y);}
+    inline int area() const {return is_empty() ? 0 : (br.x-tl.x)*(br.y-tl.y);}
     inline Point dimensions() const {return Point(width(), height());}
     inline int width() const {return br.x-tl.x;}
     inline int height() const {return br.y-tl.y;}
diff --git a/common/rfb/SMsgWriter.cxx b/common/rfb/SMsgWriter.cxx
index 9aee96d..e421508 100644
--- a/common/rfb/SMsgWriter.cxx
+++ b/common/rfb/SMsgWriter.cxx
@@ -301,7 +301,6 @@
 {
   if (needSetCursor) {
     rdr::U8* data;
-    int stride;
 
     const Cursor& cursor = cp->cursor();
 
diff --git a/common/rfb/TightEncoder.cxx b/common/rfb/TightEncoder.cxx
index 3846ae0..fe2470b 100644
--- a/common/rfb/TightEncoder.cxx
+++ b/common/rfb/TightEncoder.cxx
@@ -163,7 +163,7 @@
   int length;
 
   const rdr::U8* buffer;
-  int stride, w, h;
+  int stride, h;
 
   os = conn->getOutStream();
 
@@ -201,7 +201,7 @@
   }
 
   while (count) {
-    int iter_count;
+    unsigned int iter_count;
 
     iter_count = sizeof(rgb)/3;
     if (iter_count > count)
diff --git a/common/rfb/VNCSConnectionST.cxx b/common/rfb/VNCSConnectionST.cxx
index e261cfb..932abc0 100644
--- a/common/rfb/VNCSConnectionST.cxx
+++ b/common/rfb/VNCSConnectionST.cxx
@@ -70,8 +70,9 @@
     queryConnectTimer(this), inProcessMessages(false),
     pendingSyncFence(false), syncFence(false), fenceFlags(0),
     fenceDataLen(0), fenceData(NULL),
-    baseRTT(-1), minRTT(-1), seenCongestion(false), pingCounter(0),
-    ackedOffset(0), sentOffset(0), congWindow(0), congestionTimer(this),
+    baseRTT(-1), congWindow(0), ackedOffset(0), sentOffset(0),
+    minRTT(-1), seenCongestion(false),
+    pingCounter(0), congestionTimer(this),
     server(server_), updates(false),
     drawRenderedCursor(false), removeRenderedCursor(false),
     continuousUpdates(false), encodeManager(this),
@@ -760,7 +761,6 @@
 void VNCSConnectionST::handleRTTPong(const struct RTTInfo &rttInfo)
 {
   unsigned rtt, delay;
-  int bdp;
 
   pingCounter--;
 
@@ -1131,7 +1131,7 @@
     accessRights = accessRights | AccessPtrEvents | AccessKeyEvents | AccessView;
     break;
   case 1:
-    accessRights = accessRights & ~(AccessPtrEvents | AccessKeyEvents) | AccessView;
+    accessRights = (accessRights & ~(AccessPtrEvents | AccessKeyEvents)) | AccessView;
     break;
   case 2:
     accessRights = accessRights & ~(AccessPtrEvents | AccessKeyEvents | AccessView);
diff --git a/common/rfb/VNCServerST.cxx b/common/rfb/VNCServerST.cxx
index 51cb86c..199524e 100644
--- a/common/rfb/VNCServerST.cxx
+++ b/common/rfb/VNCServerST.cxx
@@ -544,7 +544,7 @@
   if (!deferPending)
     return true;
 
-  if (msSince(&deferStart) >= deferUpdateTime)
+  if (msSince(&deferStart) >= (unsigned)deferUpdateTime)
     return true;
 
   return false;
diff --git a/common/rfb/WinPasswdValidator.cxx b/common/rfb/WinPasswdValidator.cxx
index 7f8fbf2..22efcc0 100644
--- a/common/rfb/WinPasswdValidator.cxx
+++ b/common/rfb/WinPasswdValidator.cxx
@@ -45,7 +45,5 @@
 		return true;
 	}
 
-	int err = GetLastError();
-
 	return false;
 }
diff --git a/common/rfb/pam.c b/common/rfb/pam.c
index 67b243c..cb067fd 100644
--- a/common/rfb/pam.c
+++ b/common/rfb/pam.c
@@ -38,8 +38,13 @@
   const char *password;
 } AuthData;
 
+#if defined(__sun)
+static int pam_callback(int count, struct pam_message **in,
+                        struct pam_response **out, void *ptr)
+#else
 static int pam_callback(int count, const struct pam_message **in,
-			struct pam_response **out, void *ptr)
+                        struct pam_response **out, void *ptr)
+#endif
 {
   int i;
   AuthData *auth = (AuthData *) ptr;
diff --git a/common/rfb/util.cxx b/common/rfb/util.cxx
index a41ad96..aec45f6 100644
--- a/common/rfb/util.cxx
+++ b/common/rfb/util.cxx
@@ -34,12 +34,37 @@
 #include <config.h>
 #endif
 
+#include <stdarg.h>
+#include <stdio.h>
 #include <sys/time.h>
 
 #include <rfb/util.h>
 
 namespace rfb {
 
+  void CharArray::format(const char *fmt, ...) {
+    va_list ap;
+    size_t len;
+
+    va_start(ap, fmt);
+    len = vsnprintf(NULL, 0, fmt, ap);
+    va_end(ap);
+
+    delete [] buf;
+
+    if (len < 0) {
+      buf = new char[1];
+      buf[0] = '\0';
+      return;
+    }
+
+    buf = new char[len+1];
+
+    va_start(ap, fmt);
+    vsnprintf(buf, len+1, fmt, ap);
+    va_end(ap);
+  }
+
   char* strDup(const char* s) {
     if (!s) return 0;
     int l = strlen(s);
@@ -110,4 +135,44 @@
 
     return diff;
   }
+
+  static size_t doPrefix(long long value, const char *unit,
+                         char *buffer, size_t maxlen,
+                         unsigned divisor, const char **prefixes,
+                         size_t prefixCount) {
+    double newValue;
+    size_t prefix, len;
+
+    newValue = value;
+    prefix = 0;
+    while (newValue >= divisor) {
+      if (prefix >= prefixCount)
+        break;
+      newValue /= divisor;
+      prefix++;
+    }
+
+    len = snprintf(buffer, maxlen, "%g %s%s", newValue,
+                   (prefix == 0) ? "" : prefixes[prefix-1], unit);
+    buffer[maxlen-1] = '\0';
+
+    return len;
+  }
+
+  static const char *siPrefixes[] =
+    { "k", "M", "G", "T", "P", "E", "Z", "Y" };
+  static const char *iecPrefixes[] =
+    { "Ki", "Mi", "Gi", "Ti", "Pi", "Ei", "Zi", "Yi" };
+
+  size_t siPrefix(long long value, const char *unit,
+                  char *buffer, size_t maxlen) {
+    return doPrefix(value, unit, buffer, maxlen, 1000, siPrefixes,
+                    sizeof(siPrefixes)/sizeof(*siPrefixes));
+  }
+
+  size_t iecPrefix(long long value, const char *unit,
+                   char *buffer, size_t maxlen) {
+    return doPrefix(value, unit, buffer, maxlen, 1024, iecPrefixes,
+                    sizeof(iecPrefixes)/sizeof(*iecPrefixes));
+  }
 };
diff --git a/common/rfb/util.h b/common/rfb/util.h
index 13dbe68..9ad1772 100644
--- a/common/rfb/util.h
+++ b/common/rfb/util.h
@@ -32,6 +32,12 @@
 
 struct timeval;
 
+#ifdef __GNUC__
+#  define __printf_attr(a, b) __attribute__((__format__ (__printf__, a, b)))
+#else
+#  define __printf_attr(a, b)
+#endif // __GNUC__
+
 namespace rfb {
 
   // -=- Class to handle cleanup of arrays of characters
@@ -45,6 +51,7 @@
     ~CharArray() {
       delete [] buf;
     }
+    void format(const char *fmt, ...) __printf_attr(2, 3);
     // Get the buffer pointer & clear it (i.e. caller takes ownership)
     char* takeBuf() {char* tmp = buf; buf = 0; return tmp;}
     void replaceBuf(char* b) {delete [] buf; buf = b;}
@@ -90,6 +97,11 @@
 
   // Returns time elapsed since given moment in milliseconds.
   unsigned msSince(const struct timeval *then);
+
+  size_t siPrefix(long long value, const char *unit,
+                  char *buffer, size_t maxlen);
+  size_t iecPrefix(long long value, const char *unit,
+                   char *buffer, size_t maxlen);
 }
 
 // Some platforms (e.g. Windows) include max() and min() macros in their
diff --git a/tests/conv.cxx b/tests/conv.cxx
index 2ee523a..840f18d 100644
--- a/tests/conv.cxx
+++ b/tests/conv.cxx
@@ -266,7 +266,7 @@
 static void doTests(const rfb::PixelFormat &dstpf,
                     const rfb::PixelFormat &srcpf)
 {
-  int i;
+  size_t i;
   char dstb[256], srcb[256];
 
   dstpf.print(dstb, sizeof(dstb));
diff --git a/tests/convperf.cxx b/tests/convperf.cxx
index c8381d5..e4a3fd5 100644
--- a/tests/convperf.cxx
+++ b/tests/convperf.cxx
@@ -100,7 +100,7 @@
 
 static void doTests(rfb::PixelFormat &dstpf, rfb::PixelFormat &srcpf)
 {
-  int i;
+  size_t i;
   char dstb[256], srcb[256];
 
   dstpf.print(dstb, sizeof(dstb));
@@ -118,19 +118,19 @@
 
 int main(int argc, char **argv)
 {
-  int bufsize;
+  size_t bufsize;
 
   time_t t;
   char datebuffer[256];
 
-  int i;
+  size_t i;
 
   bufsize = fbsize * fbsize * 4;
 
   fb1 = new rdr::U8[bufsize];
   fb2 = new rdr::U8[bufsize];
 
-  for (int i = 0;i < bufsize;i++) {
+  for (i = 0;i < bufsize;i++) {
     fb1[i] = rand();
     fb2[i] = rand();
   }
diff --git a/tests/decperf.cxx b/tests/decperf.cxx
index 1d0c80c..fe7b032 100644
--- a/tests/decperf.cxx
+++ b/tests/decperf.cxx
@@ -147,7 +147,12 @@
 
   try {
     cc = new CConn(fn);
+  } catch (rdr::Exception e) {
+    fprintf(stderr, "Failed to open rfb file: %s\n", e.str());
+    exit(1);
+  }
 
+  try {
     while (true)
       cc->processMsg();
   } catch (rdr::EndOfStream e) {
@@ -211,7 +216,7 @@
   sort(dev, runCount);
   meddev = dev[runCount/2];
 
-  printf("CPU time: %g s (+/- %g %)\n", median, meddev);
+  printf("CPU time: %g s (+/- %g %%)\n", median, meddev);
 
   return 0;
 }
diff --git a/tests/encperf.cxx b/tests/encperf.cxx
index bbaa8fb..9b632e7 100644
--- a/tests/encperf.cxx
+++ b/tests/encperf.cxx
@@ -158,6 +158,9 @@
 int DummyOutStream::overrun(int itemSize, int nItems)
 {
   flush();
+  if (itemSize * nItems > end - ptr)
+    nItems = (end - ptr) / itemSize;
+  return nItems;
 }
 
 CConn::CConn(const char *filename)
@@ -339,7 +342,12 @@
 
   try {
     cc = new CConn(fn);
+  } catch (rdr::Exception e) {
+    fprintf(stderr, "Failed to open rfb file: %s\n", e.str());
+    exit(1);
+  }
 
+  try {
     while (true)
       cc->processMsg();
   } catch (rdr::EndOfStream e) {
@@ -447,8 +455,13 @@
   meddev = dev[runCount / 2];
 
   printf("CPU time: %g s (+/- %g %%)\n", median, meddev);
+#ifdef WIN32
+  printf("Encoded bytes: %I64d\n", bytes);
+  printf("Raw equivalent bytes: %I64d\n", equivalent);
+#else
   printf("Encoded bytes: %lld\n", bytes);
   printf("Raw equivalent bytes: %lld\n", equivalent);
+#endif
   printf("Ratio: %g\n", ratio);
 
   return 0;
diff --git a/tests/util.cxx b/tests/util.cxx
index 52a2c61..419f09c 100644
--- a/tests/util.cxx
+++ b/tests/util.cxx
@@ -107,7 +107,7 @@
   counters[1] = (uint64_t)s[1].dwHighDateTime << 32 |
                 s[1].dwLowDateTime;
 
-  seconds = (double)(counters[1] - counters[2]) / 10000000.0;
+  seconds = (double)(counters[1] - counters[0]) / 10000000.0;
 #else
   seconds = (double)(s[1].ru_utime.tv_sec -
                      s[0].ru_utime.tv_sec);
diff --git a/unix/vncconfig/vncExt.c b/unix/vncconfig/vncExt.c
index c2e6d3c..ff6b4d6 100644
--- a/unix/vncconfig/vncExt.c
+++ b/unix/vncconfig/vncExt.c
@@ -16,6 +16,7 @@
  * USA.
  */
 #include <stdio.h>
+#include <stdint.h>
 
 #define NEED_REPLIES
 #include <X11/Xlib.h>
@@ -277,7 +278,7 @@
   return True;
 }
 
-Bool XVncExtConnect(Display* dpy, char* hostAndPort)
+Bool XVncExtConnect(Display* dpy, const char* hostAndPort)
 {
   xVncExtConnectReq* req;
   xVncExtConnectReply rep;
@@ -328,7 +329,7 @@
   if (!*addr || !*user) {
     Xfree(*addr);
     Xfree(*user);
-    _XEatData(dpy, (rep.addrLen+1)&~1 + (rep.userLen+1)&~1);
+    _XEatData(dpy, ((rep.addrLen+1)&~1) + ((rep.userLen+1)&~1));
     return False;
   }
   _XReadPad(dpy, *addr, rep.addrLen);
@@ -336,7 +337,7 @@
   _XReadPad(dpy, *user, rep.userLen);
   (*user)[rep.userLen] = 0;
   *timeout = rep.timeout;
-  *opaqueId = (void*)rep.opaqueId;
+  *opaqueId = (void*)(intptr_t)rep.opaqueId;
   return True;
 }
 
@@ -351,7 +352,7 @@
   req->reqType = codes->major_opcode;
   req->vncExtReqType = X_VncExtApproveConnect;
   req->approve = approve;
-  req->opaqueId = (CARD32)opaqueId;
+  req->opaqueId = (CARD32)(intptr_t)opaqueId;
   UnlockDisplay(dpy);
   SyncHandle();
   return True;
diff --git a/unix/vncconfig/vncExt.h b/unix/vncconfig/vncExt.h
index f1502c4..e41e2e5 100644
--- a/unix/vncconfig/vncExt.h
+++ b/unix/vncconfig/vncExt.h
@@ -54,7 +54,7 @@
 Bool XVncExtSetServerCutText(Display* dpy, const char* str, int len);
 Bool XVncExtGetClientCutText(Display* dpy, char** str, int* len);
 Bool XVncExtSelectInput(Display* dpy, Window w, int mask);
-Bool XVncExtConnect(Display* dpy, char* hostAndPort);
+Bool XVncExtConnect(Display* dpy, const char* hostAndPort);
 Bool XVncExtGetQueryConnect(Display* dpy, char** addr,
                             char** user, int* timeout, void** opaqueId);
 Bool XVncExtApproveConnect(Display* dpy, void* opaqueId, int approve);
diff --git a/unix/x0vncserver/x0vncserver.cxx b/unix/x0vncserver/x0vncserver.cxx
index ee39fae..a9b328f 100644
--- a/unix/x0vncserver/x0vncserver.cxx
+++ b/unix/x0vncserver/x0vncserver.cxx
@@ -287,6 +287,8 @@
     server->add_changed(rect);
 
     return true;
+#else
+  return false;
 #endif
   }
 
diff --git a/vncviewer/CConn.cxx b/vncviewer/CConn.cxx
index cf4f31b..f8b45af 100644
--- a/vncviewer/CConn.cxx
+++ b/vncviewer/CConn.cxx
@@ -134,7 +134,7 @@
 {
   OptionsDialog::removeCallback(handleOptions);
 
-  for (int i = 0; i < sizeof(decoders)/sizeof(decoders[0]); i++)
+  for (size_t i = 0; i < sizeof(decoders)/sizeof(decoders[0]); i++)
     delete decoders[i];
 
   if (desktop)
@@ -313,8 +313,8 @@
 }
 
 // setExtendedDesktopSize() is a more advanced version of setDesktopSize()
-void CConn::setExtendedDesktopSize(int reason, int result, int w, int h,
-                                   const rfb::ScreenSet& layout)
+void CConn::setExtendedDesktopSize(unsigned reason, unsigned result,
+                                   int w, int h, const rfb::ScreenSet& layout)
 {
   CConnection::setExtendedDesktopSize(reason, result, w, h, layout);
 
@@ -411,7 +411,7 @@
   ret = fl_utf8froma(buffer, size, str, len);
   assert(ret < size);
 
-  vlog.debug("Got clipboard data (%d bytes)", strlen(buffer));
+  vlog.debug("Got clipboard data (%d bytes)", (int)strlen(buffer));
 
   // RFB doesn't have separate selection and clipboard concepts, so we
   // dump the data into both variants.
diff --git a/vncviewer/CConn.h b/vncviewer/CConn.h
index 709ca2f..1b92937 100644
--- a/vncviewer/CConn.h
+++ b/vncviewer/CConn.h
@@ -51,8 +51,8 @@
   void serverInit();
 
   void setDesktopSize(int w, int h);
-  void setExtendedDesktopSize(int reason, int result, int w, int h,
-                              const rfb::ScreenSet& layout);
+  void setExtendedDesktopSize(unsigned reason, unsigned result,
+                              int w, int h, const rfb::ScreenSet& layout);
 
   void setName(const char* name);
 
diff --git a/vncviewer/OptionsDialog.cxx b/vncviewer/OptionsDialog.cxx
index 9fa9a66..d1495ef 100644
--- a/vncviewer/OptionsDialog.cxx
+++ b/vncviewer/OptionsDialog.cxx
@@ -422,7 +422,7 @@
 
   int orig_tx, orig_ty;
   int half_width, full_width;
-  int width, height;
+  int height;
 
   tx += OUTER_MARGIN;
   ty += OUTER_MARGIN;
@@ -454,8 +454,6 @@
     tx += GROUP_MARGIN;
     ty += GROUP_MARGIN;
 
-    width = encodingGroup->w() - GROUP_MARGIN * 2;
-
     tightButton = new Fl_Round_Button(LBLRIGHT(tx, ty,
                                                RADIO_MIN_WIDTH,
                                                RADIO_HEIGHT,
@@ -504,8 +502,6 @@
     tx += GROUP_MARGIN;
     ty += GROUP_MARGIN;
 
-    width = colorlevelGroup->w() - GROUP_MARGIN * 2;
-
     fullcolorCheckbox = new Fl_Round_Button(LBLRIGHT(tx, ty,
                                                      RADIO_MIN_WIDTH,
                                                      RADIO_HEIGHT,
diff --git a/vncviewer/Viewport.cxx b/vncviewer/Viewport.cxx
index 6c77e58..11e7fed 100644
--- a/vncviewer/Viewport.cxx
+++ b/vncviewer/Viewport.cxx
@@ -104,7 +104,7 @@
 Viewport::Viewport(int w, int h, const rfb::PixelFormat& serverPF, CConn* cc_)
   : Fl_Widget(0, 0, w, h), cc(cc_), frameBuffer(NULL),
     lastPointerPos(0, 0), lastButtonMask(0),
-    cursor(NULL), menuCtrlKey(false), menuAltKey(false)
+    menuCtrlKey(false), menuAltKey(false), cursor(NULL)
 {
 // FLTK STR #2636 gives us the ability to monitor clipboard changes
 #ifdef HAVE_FLTK_CLIPBOARD
@@ -351,7 +351,7 @@
                      Fl::event_length() + 1);
     assert(ret < (Fl::event_length() + 1));
 
-    vlog.debug("Sending clipboard data (%d bytes)", strlen(buffer));
+    vlog.debug("Sending clipboard data (%d bytes)", (int)strlen(buffer));
 
     try {
       cc->writer()->clientCutText(buffer, ret);
diff --git a/vncviewer/X11PixelBuffer.cxx b/vncviewer/X11PixelBuffer.cxx
index 7e89a60..9196fdc 100644
--- a/vncviewer/X11PixelBuffer.cxx
+++ b/vncviewer/X11PixelBuffer.cxx
@@ -157,7 +157,6 @@
   int major, minor;
   Bool pixmaps;
   XErrorHandler old_handler;
-  Status status;
   const char *display_name = XDisplayName (NULL);
 
   /* Don't use MIT-SHM on remote displays */
diff --git a/vncviewer/cocoa.mm b/vncviewer/cocoa.mm
index 0992100..e51cba9 100644
--- a/vncviewer/cocoa.mm
+++ b/vncviewer/cocoa.mm
@@ -57,7 +57,7 @@
       if (CGGetActiveDisplayList(16, displays, &count) != kCGErrorSuccess)
         return 1;
 
-      if (count != Fl::screen_count())
+      if (count != (unsigned)Fl::screen_count())
         return 1;
 
 #ifdef HAVE_FLTK_FULLSCREEN_SCREENS
@@ -424,7 +424,7 @@
   NSEvent *nsevent;
 
   UInt16 key_code;
-  int i;
+  size_t i;
 
   NSString *chars;
   UInt32 modifiers;
diff --git a/vncviewer/keysym2ucs.c b/vncviewer/keysym2ucs.c
index d91df67..33a5653 100644
--- a/vncviewer/keysym2ucs.c
+++ b/vncviewer/keysym2ucs.c
@@ -899,7 +899,6 @@
 {
   int cur = 0;
   int max = sizeof(keysymtab) / sizeof(struct codepair) - 1;
-  int mid;
 
   /* first check for Latin-1 characters (1:1 mapping) */
   if ((ucs >= 0x0020 && ucs <= 0x007e) ||
diff --git a/vncviewer/parameters.cxx b/vncviewer/parameters.cxx
index c975e99..712a257 100644
--- a/vncviewer/parameters.cxx
+++ b/vncviewer/parameters.cxx
@@ -182,8 +182,8 @@
 static struct {
   const char first;
   const char second;
-} replaceMap[] = {'\n', 'n',
-                  '\r', 'r'};
+} replaceMap[] = { { '\n', 'n' },
+                   { '\r', 'r' } };
 
 static bool encodeValue(const char* val, char* dest, size_t destSize) {
 
@@ -202,7 +202,7 @@
 
     } else {
 
-      for (int j = 0; j < sizeof(replaceMap)/sizeof(replaceMap[0]); j++) {
+      for (size_t j = 0; j < sizeof(replaceMap)/sizeof(replaceMap[0]); j++) {
 
         if (val[i] == replaceMap[j].first) {
           dest[pos] = '\\';
@@ -242,7 +242,7 @@
     // Check for escape sequences
     if (val[i] == '\\') {
       
-      for (int j = 0; j < sizeof(replaceMap)/sizeof(replaceMap[0]); j++) {
+      for (size_t j = 0; j < sizeof(replaceMap)/sizeof(replaceMap[0]); j++) {
         if (val[i+1] == replaceMap[j].second) {
           dest[pos] = replaceMap[j].first;
           escapedCharacter = true;
@@ -303,7 +303,7 @@
 
   LONG res = RegSetValueExW(*hKey, name, 0, REG_SZ, (BYTE*)&value, (wcslen(value)+1)*2);
   if (res != ERROR_SUCCESS) {
-    vlog.error(_("Failed to write parameter %s of type %s to the registry: %d"),
+    vlog.error(_("Failed to write parameter %s of type %s to the registry: %ld"),
                _name, "REG_SZ", res);
     return;
   }
@@ -324,7 +324,7 @@
   
   LONG res = RegSetValueExW(*hKey, name, 0, REG_DWORD, (BYTE*)&value, sizeof(DWORD));
   if (res != ERROR_SUCCESS) {
-    vlog.error(_("Failed to write parameter %s of type %s to the registry: %d"),
+    vlog.error(_("Failed to write parameter %s of type %s to the registry: %ld"),
                _name, "REG_DWORD", res);
     return;
   }
@@ -348,7 +348,7 @@
     if (res == ERROR_FILE_NOT_FOUND) {
       // The value does not exist, defaults will be used.
     } else {
-      vlog.error(_("Failed to read parameter %s from the registry: %d"),
+      vlog.error(_("Failed to read parameter %s from the registry: %ld"),
                  _name, res);
     }
     return false;
@@ -387,7 +387,7 @@
     if (res == ERROR_FILE_NOT_FOUND) {
       // The value does not exist, defaults will be used.
     } else {
-      vlog.error(_("Failed to read parameter %s from the registry: %d"),
+      vlog.error(_("Failed to read parameter %s from the registry: %ld"),
                  _name, res);
     }
     return false;
@@ -407,13 +407,13 @@
                              REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL,
                              &hKey, NULL);
   if (res != ERROR_SUCCESS) {
-    vlog.error(_("Failed to create registry key: %d"), res);
+    vlog.error(_("Failed to create registry key: %ld"), res);
     return;
   }
 
   setKeyString("ServerName", servername, &hKey);
 
-  for (int i = 0; i < sizeof(parameterArray)/sizeof(VoidParameter*); i++) {
+  for (size_t i = 0; i < sizeof(parameterArray)/sizeof(VoidParameter*); i++) {
     if (dynamic_cast<StringParameter*>(parameterArray[i]) != NULL) {
       setKeyString(parameterArray[i]->getName(), *(StringParameter*)parameterArray[i], &hKey);
     } else if (dynamic_cast<IntParameter*>(parameterArray[i]) != NULL) {
@@ -428,7 +428,7 @@
 
   res = RegCloseKey(hKey);
   if (res != ERROR_SUCCESS) {
-    vlog.error(_("Failed to close registry key: %d"), res);
+    vlog.error(_("Failed to close registry key: %ld"), res);
   }
 }
 
@@ -444,7 +444,7 @@
     if (res == ERROR_FILE_NOT_FOUND) {
       // The key does not exist, defaults will be used.
     } else {
-      vlog.error(_("Failed to open registry key: %d"), res);
+      vlog.error(_("Failed to open registry key: %ld"), res);
     }
     return NULL;
   }
@@ -459,7 +459,7 @@
   int intValue = 0;
   char stringValue[buffersize];
   
-  for (int i = 0; i < sizeof(parameterArray)/sizeof(VoidParameter*); i++) {
+  for (size_t i = 0; i < sizeof(parameterArray)/sizeof(VoidParameter*); i++) {
     if (dynamic_cast<StringParameter*>(parameterArray[i]) != NULL) {
       if (getKeyString(parameterArray[i]->getName(), stringValue, buffersize, &hKey))
         parameterArray[i]->setParam(stringValue);
@@ -477,7 +477,7 @@
 
   res = RegCloseKey(hKey);
   if (res != ERROR_SUCCESS){
-    vlog.error(_("Failed to close registry key: %d"), res);
+    vlog.error(_("Failed to close registry key: %ld"), res);
   }
   
   return servername;
@@ -489,7 +489,6 @@
 
   const size_t buffersize = 256;
   char filepath[PATH_MAX];
-  char write_error[buffersize*2];
   char encodingBuffer[buffersize];
 
   // Write to the registry or a predefined file if no filename was specified.
@@ -514,12 +513,9 @@
 
   /* Write parameters to file */
   FILE* f = fopen(filepath, "w+");
-  if (!f) {
-    snprintf(write_error, sizeof(write_error),
-             _("Failed to write configuration file, can't open %s: %s"),
-             filepath, strerror(errno));
-    throw Exception(write_error);
-  }
+  if (!f)
+    throw Exception(_("Failed to write configuration file, can't open %s: %s"),
+                    filepath, strerror(errno));
   
   fprintf(f, "%s\r\n", IDENTIFIER_STRING);
   fprintf(f, "\r\n");
@@ -527,7 +523,7 @@
   if (encodeValue(servername, encodingBuffer, buffersize))  
     fprintf(f, "ServerName=%s\n", encodingBuffer);
   
-  for (int i = 0; i < sizeof(parameterArray)/sizeof(VoidParameter*); i++) {
+  for (size_t i = 0; i < sizeof(parameterArray)/sizeof(VoidParameter*); i++) {
     if (dynamic_cast<StringParameter*>(parameterArray[i]) != NULL) {
       if (encodeValue(*(StringParameter*)parameterArray[i], encodingBuffer, buffersize))
         fprintf(f, "%s=%s\n", ((StringParameter*)parameterArray[i])->getName(), encodingBuffer);
@@ -548,10 +544,8 @@
 
   const size_t buffersize = 256;
   char filepath[PATH_MAX];
-  char readError[buffersize*2];
   char line[buffersize];
   char decodingBuffer[buffersize];
-  char decodedValue[buffersize];
   static char servername[sizeof(line)];
 
   // Load from the registry or a predefined file if no filename was specified.
@@ -576,10 +570,8 @@
   if (!f) {
     if (!filename)
       return NULL; // Use defaults.
-    snprintf(readError, sizeof(readError),
-             _("Failed to read configuration file, can't open %s: %s"),
-             filepath, strerror(errno));
-    throw Exception(readError);
+    throw Exception(_("Failed to read configuration file, can't open %s: %s"),
+                    filepath, strerror(errno));
   }
   
   int lineNr = 0;
@@ -588,31 +580,23 @@
     // Read the next line
     lineNr++;
     if (!fgets(line, sizeof(line), f)) {
-      if (line[sizeof(line) -1] != '\0') {
-        snprintf(readError, sizeof(readError),
-                 _("Failed to read line %d in file %s: %s"),
-                 lineNr, filepath, _("Line too long"));
-        throw Exception(readError);
-      }
+      if (line[sizeof(line) -1] != '\0')
+        throw Exception(_("Failed to read line %d in file %s: %s"),
+                        lineNr, filepath, _("Line too long"));
       if (feof(f))
         break;
 
-      snprintf(readError, sizeof(readError),
-               _("Failed to read line %d in file %s: %s"),
-               lineNr, filepath, strerror(errno));
-      throw Exception(readError);
+      throw Exception(_("Failed to read line %d in file %s: %s"),
+                      lineNr, filepath, strerror(errno));
     }
     
     // Make sure that the first line of the file has the file identifier string
     if(lineNr == 1) {
-      if(strncmp(line, IDENTIFIER_STRING, strlen(IDENTIFIER_STRING)) == 0) {
+      if(strncmp(line, IDENTIFIER_STRING, strlen(IDENTIFIER_STRING)) == 0)
         continue;
-      } else {
-        snprintf(readError, sizeof(readError),
-                 _("Configuration file %s is in an invalid format"),
-                 filepath);
-        throw Exception(readError);
-      }
+      else
+        throw Exception(_("Configuration file %s is in an invalid format"),
+                        filepath);
     }
     
     // Skip empty lines and comments
@@ -651,7 +635,7 @@
     } else {
     
       // Find and set the correct parameter
-      for (int i = 0; i < sizeof(parameterArray)/sizeof(VoidParameter*); i++) {
+      for (size_t i = 0; i < sizeof(parameterArray)/sizeof(VoidParameter*); i++) {
 
         if (dynamic_cast<StringParameter*>(parameterArray[i]) != NULL) {
           if (strcasecmp(line, ((StringParameter*)parameterArray[i])->getName()) == 0) {
diff --git a/vncviewer/vncviewer.cxx b/vncviewer/vncviewer.cxx
index 936a22a..a60f000 100644
--- a/vncviewer/vncviewer.cxx
+++ b/vncviewer/vncviewer.cxx
@@ -79,10 +79,6 @@
 using namespace rfb;
 using namespace std;
 
-static const char _aboutText[] = N_("TigerVNC Viewer %d-bit v%s\n"
-                                    "Built on: %s\n"
-                                    "Copyright (C) 1999-%d TigerVNC Team and many others (see README.txt)\n"
-                                    "See http://www.tigervnc.org for information on TigerVNC.");
 static char aboutText[1024];
 
 char vncServerName[VNCSERVERNAMELEN] = { '\0' };
@@ -382,7 +378,11 @@
   textdomain(PACKAGE_NAME);
 
   // Generate the about string now that we get the proper translation
-  snprintf(aboutText, sizeof(aboutText), _aboutText,
+  snprintf(aboutText, sizeof(aboutText),
+           _("TigerVNC Viewer %d-bit v%s\n"
+             "Built on: %s\n"
+             "Copyright (C) 1999-%d TigerVNC Team and many others (see README.txt)\n"
+             "See http://www.tigervnc.org for information on TigerVNC."),
            (int)sizeof(size_t)*8, PACKAGE_VERSION,
            BUILD_TIMESTAMP, 2015);
 
@@ -425,6 +425,7 @@
   try {
     defaultServerName = loadViewerParameters(NULL);
   } catch (rfb::Exception& e) {
+    defaultServerName = "";
     fl_alert("%s", e.str());
   }
   
diff --git a/win/resdefs.h.in b/win/resdefs.h.in
index b61db53..e86a92d 100644
--- a/win/resdefs.h.in
+++ b/win/resdefs.h.in
@@ -1,4 +1,3 @@
 #define __VERSIONSTR "@VERSION@\0"
 #define __RCVERSION @RCVERSION@
 #define __RCVERSIONSTR "@RCVERSION@\0"
-#cmakedefine WIN64
diff --git a/win/rfb_win32/CleanDesktop.cxx b/win/rfb_win32/CleanDesktop.cxx
index 52dc6bd..8009fc8 100644
--- a/win/rfb_win32/CleanDesktop.cxx
+++ b/win/rfb_win32/CleanDesktop.cxx
@@ -129,7 +129,7 @@
         vlog.error("failed to get desktop item count: %ld", hr);
         return false;
       }
-      for (unsigned int i=0; i<itemCount; i++) {
+      for (int i=0; i<itemCount; i++) {
         if (enableItem(i, false))
           restoreItems.insert(i);
       }
@@ -148,7 +148,7 @@
   DWORD r = ERROR_SUCCESS;
   if (!SystemParametersInfo(action, param, ptr, ini)) {
     r = GetLastError();
-    vlog.info("SPI error: %d", r);
+    vlog.info("SPI error: %lu", r);
   }
   return r;
 }
@@ -303,12 +303,12 @@
       desktopCfg.openKey(HKEY_CURRENT_USER, _T("Control Panel\\Desktop"));
       SysParamsInfo(SPI_SETFONTSMOOTHING, desktopCfg.getInt(_T("FontSmoothing"), 0) != 0, 0, SPIF_SENDCHANGE);
 #ifdef RFB_HAVE_SPI_UIEFFECTS
-      if (SysParamsInfo(SPI_SETUIEFFECTS, 0, (void*)uiEffects, SPIF_SENDCHANGE) == ERROR_CALL_NOT_IMPLEMENTED) {
-        SysParamsInfo(SPI_SETCOMBOBOXANIMATION, 0, (void*)comboBoxAnim, SPIF_SENDCHANGE);
-        SysParamsInfo(SPI_SETGRADIENTCAPTIONS, 0, (void*)gradientCaptions, SPIF_SENDCHANGE);
-        SysParamsInfo(SPI_SETHOTTRACKING, 0, (void*)hotTracking, SPIF_SENDCHANGE);
-        SysParamsInfo(SPI_SETLISTBOXSMOOTHSCROLLING, 0, (void*)listBoxSmoothScroll, SPIF_SENDCHANGE);
-        SysParamsInfo(SPI_SETMENUANIMATION, 0, (void*)menuAnim, SPIF_SENDCHANGE);
+      if (SysParamsInfo(SPI_SETUIEFFECTS, 0, (void*)(intptr_t)uiEffects, SPIF_SENDCHANGE) == ERROR_CALL_NOT_IMPLEMENTED) {
+        SysParamsInfo(SPI_SETCOMBOBOXANIMATION, 0, (void*)(intptr_t)comboBoxAnim, SPIF_SENDCHANGE);
+        SysParamsInfo(SPI_SETGRADIENTCAPTIONS, 0, (void*)(intptr_t)gradientCaptions, SPIF_SENDCHANGE);
+        SysParamsInfo(SPI_SETHOTTRACKING, 0, (void*)(intptr_t)hotTracking, SPIF_SENDCHANGE);
+        SysParamsInfo(SPI_SETLISTBOXSMOOTHSCROLLING, 0, (void*)(intptr_t)listBoxSmoothScroll, SPIF_SENDCHANGE);
+        SysParamsInfo(SPI_SETMENUANIMATION, 0, (void*)(intptr_t)menuAnim, SPIF_SENDCHANGE);
       }
       restoreEffects = false;
 #else
diff --git a/win/rfb_win32/Clipboard.cxx b/win/rfb_win32/Clipboard.cxx
index 482519e..0e29062 100644
--- a/win/rfb_win32/Clipboard.cxx
+++ b/win/rfb_win32/Clipboard.cxx
@@ -87,7 +87,7 @@
 }
 
 Clipboard::~Clipboard() {
-  vlog.debug("removing %x from chain (next is %x)", getHandle(), next_window);
+  vlog.debug("removing %p from chain (next is %p)", getHandle(), next_window);
   ChangeClipboardChain(getHandle(), next_window);
 }
 
@@ -96,7 +96,8 @@
   switch (msg) {
 
   case WM_CHANGECBCHAIN:
-    vlog.debug("change clipboard chain (%x, %x)", wParam, lParam);
+    vlog.debug("change clipboard chain (%I64x, %I64x)",
+               (long long)wParam, (long long)lParam);
     if ((HWND) wParam == next_window)
       next_window = (HWND) lParam;
     else if (next_window != 0)
@@ -111,7 +112,7 @@
       if (owner == getHandle()) {
         vlog.debug("local clipboard changed by me");
       } else {
-        vlog.debug("local clipboard changed by %x", owner);
+        vlog.debug("local clipboard changed by %p", owner);
 
 			  // Open the clipboard
 			  if (OpenClipboard(getHandle())) {
@@ -190,7 +191,7 @@
 
   // - Close the clipboard
   if (!CloseClipboard())
-    vlog.debug("unable to close Win32 clipboard: %u", GetLastError());
+    vlog.debug("unable to close Win32 clipboard: %lu", GetLastError());
   else
     vlog.debug("closed clipboard");
   if (clip_handle) {
diff --git a/win/rfb_win32/DeviceContext.cxx b/win/rfb_win32/DeviceContext.cxx
index 26721a6..da19de8 100644
--- a/win/rfb_win32/DeviceContext.cxx
+++ b/win/rfb_win32/DeviceContext.cxx
@@ -91,7 +91,7 @@
       rMask = bi.mask.red;
       gMask = bi.mask.green;
       bMask = bi.mask.blue;
-      vlog.info("%lu-bit BitFields: (%lx, %lx, %lx)",
+      vlog.info("%d-bit BitFields: (%lx, %lx, %lx)",
                  bi.bmiHeader.biBitCount, rMask, gMask, bMask);
       break;
     };
@@ -127,6 +127,10 @@
     if (bpp < 8)
       bpp = 8;
     vlog.info("%d-colour palettised", 1<<depth);
+    // Aren't really used, but set them to keep the compiler happy
+    redMax = redShift = 0;
+    greenMax = greenShift = 0;
+    blueMax = blueShift = 0;
   }
 
 
diff --git a/win/rfb_win32/Dialog.cxx b/win/rfb_win32/Dialog.cxx
index 70a5fb5..6b52244 100644
--- a/win/rfb_win32/Dialog.cxx
+++ b/win/rfb_win32/Dialog.cxx
@@ -278,7 +278,7 @@
     if ((handle == 0) || (handle == (HWND)-1))
       throw rdr::SystemException("PropertySheet failed", GetLastError());
     centerWindow(handle, owner);
-    plog.info("created %lx", handle);
+    plog.info("created %p", handle);
 
 #ifdef _DIALOG_CAPTURE
     if (capture) {
@@ -336,7 +336,7 @@
     }
 #endif
 
-    plog.info("finished %lx", handle);
+    plog.info("finished %p", handle);
 
     DestroyWindow(handle);
     handle = 0;
@@ -361,7 +361,7 @@
 }
 
 void PropSheet::reInitPages() {
-  plog.debug("reInitPages %lx", handle);
+  plog.debug("reInitPages %p", handle);
   std::list<PropSheetPage*>::iterator pspi;
   for (pspi=pages.begin(); pspi!=pages.end(); pspi++) {
     if ((*pspi)->handle)
@@ -370,7 +370,7 @@
 }
 
 bool PropSheet::commitPages() {
-  plog.debug("commitPages %lx", handle);
+  plog.debug("commitPages %p", handle);
   bool result = true;
   std::list<PropSheetPage*>::iterator pspi;
   for (pspi=pages.begin(); pspi!=pages.end(); pspi++) {
@@ -383,7 +383,7 @@
 
 void PropSheetPage::setChanged(bool changed) {
   if (propSheet) {
-    plog.debug("setChanged[%lx(%lx)]=%d", handle, propSheet->handle, (int)changed);
+    plog.debug("setChanged[%p(%p)]=%d", handle, propSheet->handle, (int)changed);
     if (changed)
       PropSheet_Changed(propSheet->handle, handle);
     else
diff --git a/win/rfb_win32/DynamicFn.cxx b/win/rfb_win32/DynamicFn.cxx
index 033971d..97d17ff 100644
--- a/win/rfb_win32/DynamicFn.cxx
+++ b/win/rfb_win32/DynamicFn.cxx
@@ -29,12 +29,12 @@
 DynamicFnBase::DynamicFnBase(const TCHAR* dllName, const char* fnName) : fnPtr(0), dllHandle(0) {
   dllHandle = LoadLibrary(dllName);
   if (!dllHandle) {
-    vlog.info("DLL %s not found (%d)", (const char*)CStr(dllName), GetLastError());
+    vlog.info("DLL %s not found (%lu)", (const char*)CStr(dllName), GetLastError());
     return;
   }
   fnPtr = (void*) GetProcAddress(dllHandle, fnName);
   if (!fnPtr)
-    vlog.info("proc %s not found in %s (%d)", fnName, (const char*)CStr(dllName), GetLastError());
+    vlog.info("proc %s not found in %s (%lu)", fnName, (const char*)CStr(dllName), GetLastError());
 }
 
 DynamicFnBase::~DynamicFnBase() {
diff --git a/win/rfb_win32/ListViewControl.cxx b/win/rfb_win32/ListViewControl.cxx
index bd375e2..f7733f7 100644
--- a/win/rfb_win32/ListViewControl.cxx
+++ b/win/rfb_win32/ListViewControl.cxx
@@ -30,7 +30,7 @@
 BOOL ListViewControl::InitLVColumns(DWORD idListView, HWND hDlg, int width, int columns,
                                     TCHAR *title[], DWORD mask, DWORD LVStyle, DWORD format)
 {
-  ListView_SetExtendedListViewStyle(GetDlgItem(hDlg, idListView), LVStyle);
+  (void)ListView_SetExtendedListViewStyle(GetDlgItem(hDlg, idListView), LVStyle);
   TCHAR szText[256];      
   LVCOLUMN lvc; 
   int iCol;
@@ -90,12 +90,12 @@
 
 void ListViewControl::DeleteLVItem(DWORD idListView, HWND hDlg, int number)
 {
-  ListView_DeleteItem(GetDlgItem(hDlg, idListView), number);
+  (void)ListView_DeleteItem(GetDlgItem(hDlg, idListView), number);
 }
 
 void ListViewControl::DeleteAllLVItem(DWORD idListView, HWND hDlg)
 {
-  ListView_DeleteAllItems(GetDlgItem(hDlg, idListView));
+  (void)ListView_DeleteAllItems(GetDlgItem(hDlg, idListView));
 }
 
 ListViewControl::~ListViewControl()
diff --git a/win/rfb_win32/MonitorInfo.cxx b/win/rfb_win32/MonitorInfo.cxx
index c57cd26..d639ac5 100644
--- a/win/rfb_win32/MonitorInfo.cxx
+++ b/win/rfb_win32/MonitorInfo.cxx
@@ -50,15 +50,15 @@
 typedef BOOL (WINAPI *_EnumDisplayMonitors_proto)(HDC, LPCRECT, MONITORENUMPROC, LPARAM);
 static rfb::win32::DynamicFn<_EnumDisplayMonitors_proto> _EnumDisplayMonitors(_T("user32.dll"), "EnumDisplayMonitors");
 static void fillMonitorInfo(HMONITOR monitor, MonitorInfo* mi) {
-  vlog.debug("monitor=%lx", monitor);
+  vlog.debug("monitor=%p", monitor);
   if (!_GetMonitorInfo.isValid())
     throw rdr::Exception("no GetMonitorInfo");
   memset(mi, 0, sizeof(MONITORINFOEXA));
   mi->cbSize = sizeof(MONITORINFOEXA);
   if (!(*_GetMonitorInfo)(monitor, mi))
     throw rdr::SystemException("failed to GetMonitorInfo", GetLastError());
-  vlog.debug("monitor is %d,%d-%d,%d", mi->rcMonitor.left, mi->rcMonitor.top, mi->rcMonitor.right, mi->rcMonitor.bottom);
-  vlog.debug("work area is %d,%d-%d,%d", mi->rcWork.left, mi->rcWork.top, mi->rcWork.right, mi->rcWork.bottom);
+  vlog.debug("monitor is %ld,%ld-%ld,%ld", mi->rcMonitor.left, mi->rcMonitor.top, mi->rcMonitor.right, mi->rcMonitor.bottom);
+  vlog.debug("work area is %ld,%ld-%ld,%ld", mi->rcWork.left, mi->rcWork.top, mi->rcWork.right, mi->rcWork.bottom);
   vlog.debug("device is \"%s\"", mi->szDevice);
 }
 #else
diff --git a/win/rfb_win32/MsgWindow.cxx b/win/rfb_win32/MsgWindow.cxx
index 4c50c2f..8086bea 100644
--- a/win/rfb_win32/MsgWindow.cxx
+++ b/win/rfb_win32/MsgWindow.cxx
@@ -52,7 +52,7 @@
     SetWindowLongPtr(wnd, GWLP_USERDATA, 0);
   MsgWindow* _this = (MsgWindow*) GetWindowLongPtr(wnd, GWLP_USERDATA);
   if (!_this) {
-    vlog.info("null _this in %x, message %x", wnd, msg);
+    vlog.info("null _this in %p, message %x", wnd, msg);
     return SafeDefWindowProc(wnd, msg, wParam, lParam);
   }
 
@@ -85,7 +85,7 @@
 
 MsgWindowClass::~MsgWindowClass() {
   if (classAtom) {
-    UnregisterClass((const TCHAR*)classAtom, instance);
+    UnregisterClass((const TCHAR*)(intptr_t)classAtom, instance);
   }
 }
 
@@ -97,18 +97,19 @@
 
 MsgWindow::MsgWindow(const TCHAR* name_) : name(tstrDup(name_)), handle(0) {
   vlog.debug("creating window \"%s\"", (const char*)CStr(name.buf));
-  handle = CreateWindow((const TCHAR*)baseClass.classAtom, name.buf, WS_OVERLAPPED,
-    0, 0, 10, 10, 0, 0, baseClass.instance, this);
+  handle = CreateWindow((const TCHAR*)(intptr_t)baseClass.classAtom,
+                        name.buf, WS_OVERLAPPED, 0, 0, 10, 10, 0, 0,
+                        baseClass.instance, this);
   if (!handle) {
     throw rdr::SystemException("unable to create WMNotifier window instance", GetLastError());
   }
-  vlog.debug("created window \"%s\" (%x)", (const char*)CStr(name.buf), handle);
+  vlog.debug("created window \"%s\" (%p)", (const char*)CStr(name.buf), handle);
 }
 
 MsgWindow::~MsgWindow() {
   if (handle)
     DestroyWindow(handle);
-  vlog.debug("destroyed window \"%s\" (%x)", (const char*)CStr(name.buf), handle); 
+  vlog.debug("destroyed window \"%s\" (%p)", (const char*)CStr(name.buf), handle);
 }
 
 LRESULT
diff --git a/win/rfb_win32/Registry.cxx b/win/rfb_win32/Registry.cxx
index b278576..70083f4 100644
--- a/win/rfb_win32/Registry.cxx
+++ b/win/rfb_win32/Registry.cxx
@@ -51,7 +51,7 @@
   LONG result = RegOpenKeyEx(k, 0, 0, KEY_ALL_ACCESS, &key);
   if (result != ERROR_SUCCESS)
     throw rdr::SystemException("RegOpenKeyEx(HKEY)", result);
-  vlog.debug("duplicated %x to %x", k, key);
+  vlog.debug("duplicated %p to %p", k, key);
   freeKey = true;
 }
 
@@ -59,7 +59,7 @@
   LONG result = RegOpenKeyEx(k.key, 0, 0, KEY_ALL_ACCESS, &key);
   if (result != ERROR_SUCCESS)
     throw rdr::SystemException("RegOpenKeyEx(RegKey&)", result);
-  vlog.debug("duplicated %x to %x", k.key, key);
+  vlog.debug("duplicated %p to %p", k.key, key);
   freeKey = true;
 }
 
@@ -69,7 +69,7 @@
 
 
 void RegKey::setHKEY(HKEY k, bool fK) {
-  vlog.debug("setHKEY(%x,%d)", k, (int)fK);
+  vlog.debug("setHKEY(%p,%d)", k, (int)fK);
   close();
   freeKey = fK;
   key = k;
@@ -80,10 +80,10 @@
   close();
   LONG result = RegCreateKey(root.key, name, &key);
   if (result != ERROR_SUCCESS) {
-    vlog.error("RegCreateKey(%x, %s): %x", root.key, name, result);
+    vlog.error("RegCreateKey(%p, %s): %lx", root.key, name, result);
     throw rdr::SystemException("RegCreateKeyEx", result);
   }
-  vlog.debug("createKey(%x,%s) = %x", root.key, (const char*)CStr(name), key);
+  vlog.debug("createKey(%p,%s) = %p", root.key, (const char*)CStr(name), key);
   freeKey = true;
   return true;
 }
@@ -93,7 +93,7 @@
   LONG result = RegOpenKeyEx(root.key, name, 0, readOnly ? KEY_READ : KEY_ALL_ACCESS, &key);
   if (result != ERROR_SUCCESS)
     throw rdr::SystemException("RegOpenKeyEx (open)", result);
-  vlog.debug("openKey(%x,%s,%s) = %x", root.key, (const char*)CStr(name),
+  vlog.debug("openKey(%p,%s,%s) = %p", root.key, (const char*)CStr(name),
 	         readOnly ? "ro" : "rw", key);
   freeKey = true;
 }
@@ -113,7 +113,7 @@
 
 void RegKey::close() {
   if (freeKey) {
-    vlog.debug("RegCloseKey(%x)", key);
+    vlog.debug("RegCloseKey(%p)", key);
     RegCloseKey(key);
     key = 0;
   }
diff --git a/win/rfb_win32/SInput.cxx b/win/rfb_win32/SInput.cxx
index aa8a21b..f634566 100644
--- a/win/rfb_win32/SInput.cxx
+++ b/win/rfb_win32/SInput.cxx
@@ -151,7 +151,7 @@
         flags &= ~MOUSEEVENTF_ABSOLUTE;
         SystemParametersInfo(SPI_GETMOUSE, 0, &mouseInfo, 0);
         SystemParametersInfo(SPI_GETMOUSESPEED, 0, &oldSpeed, 0);
-        vlog.debug("SPI_GETMOUSE %d, %d, %d, speed %d", mouseInfo[0], mouseInfo[1], mouseInfo[2], oldSpeed);
+        vlog.debug("SPI_GETMOUSE %lu, %lu, %lu, speed %lu", mouseInfo[0], mouseInfo[1], mouseInfo[2], oldSpeed);
         ULONG idealMouseInfo[] = {10, 0, 0};
         SystemParametersInfo(SPI_SETMOUSESPEED, 0, &newSpeed, 0);
         SystemParametersInfo(SPI_SETMOUSE, 0, &idealMouseInfo, 0);
@@ -266,7 +266,7 @@
 // the appropriate scancode corresponding to the supplied virtual keycode.
 
 inline void doKeyboardEvent(BYTE vkCode, DWORD flags) {
-  vlog.debug("vkCode 0x%x flags 0x%x", vkCode, flags);
+  vlog.debug("vkCode 0x%x flags 0x%lx", vkCode, flags);
   keybd_event(vkCode, MapVirtualKey(vkCode, 0), flags, 0);
 }
 
diff --git a/win/rfb_win32/Security.cxx b/win/rfb_win32/Security.cxx
index 95ef1d8..cad1325 100644
--- a/win/rfb_win32/Security.cxx
+++ b/win/rfb_win32/Security.cxx
@@ -112,7 +112,7 @@
   LookupAccountSid(0, (PSID)buf, 0, &nameLen, 0, &domainLen, &use);
   if (GetLastError() != ERROR_INSUFFICIENT_BUFFER)
     throw rdr::SystemException("Unable to determine SID name lengths", GetLastError());
-  vlog.info("nameLen=%d, domainLen=%d, use=%d", nameLen, domainLen, use);
+  vlog.info("nameLen=%lu, domainLen=%lu, use=%d", nameLen, domainLen, use);
   *name = new TCHAR[nameLen];
   *domain = new TCHAR[domainLen];
   if (!LookupAccountSid(0, (PSID)buf, *name, &nameLen, *domain, &domainLen, &use))
@@ -122,7 +122,7 @@
 
 Sid::Administrators::Administrators() {
   PSID sid = 0;
-  SID_IDENTIFIER_AUTHORITY ntAuth = SECURITY_NT_AUTHORITY;
+  SID_IDENTIFIER_AUTHORITY ntAuth = { SECURITY_NT_AUTHORITY };
   if (!AllocateAndInitializeSid(&ntAuth, 2,
                                 SECURITY_BUILTIN_DOMAIN_RID,
                                 DOMAIN_ALIAS_RID_ADMINS,
@@ -134,7 +134,7 @@
 
 Sid::SYSTEM::SYSTEM() {
   PSID sid = 0;
-  SID_IDENTIFIER_AUTHORITY ntAuth = SECURITY_NT_AUTHORITY;
+  SID_IDENTIFIER_AUTHORITY ntAuth = { SECURITY_NT_AUTHORITY };
   if (!AllocateAndInitializeSid(&ntAuth, 1,
                                 SECURITY_LOCAL_SYSTEM_RID,
                                 0, 0, 0, 0, 0, 0, 0, &sid))
diff --git a/win/rfb_win32/Service.cxx b/win/rfb_win32/Service.cxx
index 89be92e..99b3eaa 100644
--- a/win/rfb_win32/Service.cxx
+++ b/win/rfb_win32/Service.cxx
@@ -99,7 +99,7 @@
     vlog.error("failed to register handler: %lu", err);
     ExitProcess(err);
   }
-  vlog.debug("registered handler (%lx)", service->status_handle);
+  vlog.debug("registered handler (%p)", service->status_handle);
   service->setStatus(SERVICE_START_PENDING);
   vlog.debug("entering %s serviceMain", service->getName());
   service->status.dwWin32ExitCode = service->serviceMain(dwArgc, lpszArgv);
@@ -132,7 +132,7 @@
     entry[1].lpServiceProc = NULL;
     vlog.debug("entering dispatcher");
     if (!SetProcessShutdownParameters(0x100, 0))
-      vlog.error("unable to set shutdown parameters: %d", GetLastError());
+      vlog.error("unable to set shutdown parameters: %lu", GetLastError());
     service = this;
     if (!StartServiceCtrlDispatcher(entry))
       throw SystemException("unable to start service", GetLastError());
@@ -176,9 +176,9 @@
   if (!SetServiceStatus(status_handle, &status)) {
     status.dwCurrentState = SERVICE_STOPPED;
     status.dwWin32ExitCode = GetLastError();
-    vlog.error("unable to set service status:%u", status.dwWin32ExitCode);
+    vlog.error("unable to set service status:%lu", status.dwWin32ExitCode);
   }
-  vlog.debug("set status to %u(%u)", state, status.dwCheckPoint);
+  vlog.debug("set status to %lu(%lu)", state, status.dwCheckPoint);
 }
 
 Service::~Service() {
@@ -200,11 +200,11 @@
 switchToDesktop(HDESK desktop) {
   HDESK old_desktop = GetThreadDesktop(GetCurrentThreadId());
   if (!SetThreadDesktop(desktop)) {
-    vlog.debug("switchToDesktop failed:%u", GetLastError());
+    vlog.debug("switchToDesktop failed:%lu", GetLastError());
     return false;
   }
   if (!CloseDesktop(old_desktop))
-    vlog.debug("unable to close old desktop:%u", GetLastError());
+    vlog.debug("unable to close old desktop:%lu", GetLastError());
   return true;
 }
 
@@ -218,7 +218,7 @@
 		DESKTOP_WRITEOBJECTS | DESKTOP_READOBJECTS |
 		DESKTOP_SWITCHDESKTOP | GENERIC_WRITE);
   if (!input) {
-    vlog.debug("unable to OpenInputDesktop(1):%u", GetLastError());
+    vlog.debug("unable to OpenInputDesktop(1):%lu", GetLastError());
     return false;
   }
 
@@ -227,17 +227,17 @@
   char inputname[256];
 
   if (!GetUserObjectInformation(current, UOI_NAME, currentname, 256, &size)) {
-    vlog.debug("unable to GetUserObjectInformation(1):%u", GetLastError());
+    vlog.debug("unable to GetUserObjectInformation(1):%lu", GetLastError());
     CloseDesktop(input);
     return false;
   }
   if (!GetUserObjectInformation(input, UOI_NAME, inputname, 256, &size)) {
-    vlog.debug("unable to GetUserObjectInformation(2):%u", GetLastError());
+    vlog.debug("unable to GetUserObjectInformation(2):%lu", GetLastError());
     CloseDesktop(input);
     return false;
   }
   if (!CloseDesktop(input))
-    vlog.debug("unable to close input desktop:%u", GetLastError());
+    vlog.debug("unable to close input desktop:%lu", GetLastError());
 
   // *** vlog.debug("current=%s, input=%s", currentname, inputname);
   bool result = strcmp(currentname, inputname) == 0;
@@ -254,7 +254,7 @@
 		DESKTOP_WRITEOBJECTS | DESKTOP_READOBJECTS |
 		DESKTOP_SWITCHDESKTOP | GENERIC_WRITE);
   if (!desktop) {
-    vlog.debug("unable to OpenInputDesktop(2):%u", GetLastError());
+    vlog.debug("unable to OpenInputDesktop(2):%lu", GetLastError());
     return false;
   }
 
diff --git a/win/rfb_win32/Threading.cxx b/win/rfb_win32/Threading.cxx
index 7960766..5873b58 100644
--- a/win/rfb_win32/Threading.cxx
+++ b/win/rfb_win32/Threading.cxx
@@ -34,11 +34,11 @@
 
 
 inline void logAction(Thread* t, const char* action) {
-  vlog.debug("%-16.16s %s(%lx)", action, t->getName(), t);
+  vlog.debug("%-16.16s %s(%p)", action, t->getName(), t);
 }
 
 inline void logError(Thread* t, const char* err) {
-  vlog.error("%-16.16s %s(%lx):%s", "failed", t->getName(), t, err);
+  vlog.error("%-16.16s %s(%p):%s", "failed", t->getName(), t, err);
 }
 
 
diff --git a/win/rfb_win32/TsSessions.cxx b/win/rfb_win32/TsSessions.cxx
index efe7564..b02f619 100644
--- a/win/rfb_win32/TsSessions.cxx
+++ b/win/rfb_win32/TsSessions.cxx
@@ -48,7 +48,7 @@
     id = 0;
     if (!_ProcessIdToSessionId.isValid())
       return;
-    if (processId == -1)
+    if (processId == (DWORD)-1)
       processId = GetCurrentProcessId();
     if (!(*_ProcessIdToSessionId)(GetCurrentProcessId(), &id))
       throw rdr::SystemException("ProcessIdToSessionId", GetLastError());
@@ -72,12 +72,12 @@
 #ifdef RFB_HAVE_WINSTATION_CONNECT
     if (!_WinStationConnect.isValid())
       throw rdr::Exception("WinSta APIs missing");
-    if (sessionId == -1)
+    if (sessionId == (DWORD)-1)
       sessionId = mySessionId.id;
 
     // Try to reconnect our session to the console
     ConsoleSessionId console;
-    vlog.info("Console session is %d", console.id);
+    vlog.info("Console session is %lu", console.id);
     if (!(*_WinStationConnect)(0, sessionId, console.id, L"", 0))
       throw rdr::SystemException("Unable to connect session to Console", GetLastError());
 
diff --git a/win/rfb_win32/WMCursor.cxx b/win/rfb_win32/WMCursor.cxx
index 4d696cb..fa15833 100644
--- a/win/rfb_win32/WMCursor.cxx
+++ b/win/rfb_win32/WMCursor.cxx
@@ -49,7 +49,8 @@
 #ifdef RFB_HAVE_GETCURSORINFO
   // Check the OS version
   bool is_win98 = (osVersion.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS) &&
-    (osVersion.dwMajorVersion > 4) || ((osVersion.dwMajorVersion == 4) && (osVersion.dwMinorVersion > 0));
+    ((osVersion.dwMajorVersion > 4) ||
+     ((osVersion.dwMajorVersion == 4) && (osVersion.dwMinorVersion > 0)));
   bool is_win2K = (osVersion.dwPlatformId == VER_PLATFORM_WIN32_NT) && (osVersion.dwMajorVersion >= 5);
 
   // Use GetCursorInfo if OS version is sufficient
diff --git a/win/rfb_win32/WMShatter.cxx b/win/rfb_win32/WMShatter.cxx
index e68abfb..687deda 100644
--- a/win/rfb_win32/WMShatter.cxx
+++ b/win/rfb_win32/WMShatter.cxx
@@ -37,7 +37,8 @@
     break;
   };
   if (!result) {
-    vlog.info("IsSafeWM: 0x%x received 0x%x(%u, %lu) - not safe", window, msg, wParam, lParam);
+    vlog.info("IsSafeWM: 0x%p received 0x%x(%I64u, %I64u) - not safe",
+              window, msg, (long long)wParam, (long long)lParam);
   }
   return result;
 }
diff --git a/win/vncconfig/Connections.h b/win/vncconfig/Connections.h
index 209e4fd..6176f3d 100644
--- a/win/vncconfig/Connections.h
+++ b/win/vncconfig/Connections.h
@@ -117,11 +117,11 @@
         case IDC_HOSTS:
           {
             DWORD selected = SendMessage(GetDlgItem(handle, IDC_HOSTS), LB_GETCURSEL, 0, 0);
-            int count = SendMessage(GetDlgItem(handle, IDC_HOSTS), LB_GETCOUNT, 0, 0);
-            bool enable = selected != LB_ERR;
+            DWORD count = SendMessage(GetDlgItem(handle, IDC_HOSTS), LB_GETCOUNT, 0, 0);
+            bool enable = selected != (DWORD)LB_ERR;
             enableItem(IDC_HOST_REMOVE, enable);
             enableItem(IDC_HOST_UP, enable && (selected > 0));
-            enableItem(IDC_HOST_DOWN, enable && (selected < count-1));
+            enableItem(IDC_HOST_DOWN, enable && (selected+1 < count));
             enableItem(IDC_HOST_EDIT, enable);
             setChanged(isChanged());
           }
diff --git a/win/winvnc/ControlPanel.cxx b/win/winvnc/ControlPanel.cxx
index 9c850d3..ba6cab2 100644
--- a/win/winvnc/ControlPanel.cxx
+++ b/win/winvnc/ControlPanel.cxx
@@ -141,17 +141,16 @@
 {
   COPYDATASTRUCT copyData;
   copyData.dwData = command;
-  copyData.lpData = 0;
   getSelConnInfo();
   if (data != -1) {
     ListConnStatus.Copy(&ListSelConn);
     ListConnStatus.setAllStatus(data);
     ListConnStatus.setDisable(isItemChecked(IDC_DISABLE_CLIENTS));
-    copyData.cbData = (DWORD)((long long)&ListConnStatus);
   } else {
     ListConnStatus.Clear();
   }
-  copyData.cbData = (DWORD)((long long)&ListConnStatus);
+  copyData.cbData = 0;
+  copyData.lpData = &ListConnStatus;
   SendMessage(m_hSTIcon, WM_COPYDATA, 0, (LPARAM)&copyData);
 }
 
diff --git a/win/winvnc/ManagedListener.cxx b/win/winvnc/ManagedListener.cxx
index f2933bb..e7728bc 100644
--- a/win/winvnc/ManagedListener.cxx
+++ b/win/winvnc/ManagedListener.cxx
@@ -79,7 +79,7 @@
     if (port)
       sock = new network::TcpListener(NULL, port, localOnly);
   } catch (rdr::Exception& e) {
-    vlog.error(e.str());
+    vlog.error("%s", e.str());
   }
   if (sock) {
     if (!localOnly)
diff --git a/win/winvnc/STrayIcon.cxx b/win/winvnc/STrayIcon.cxx
index 84575bd..762a56a 100644
--- a/win/winvnc/STrayIcon.cxx
+++ b/win/winvnc/STrayIcon.cxx
@@ -63,9 +63,9 @@
 
 class STrayIcon : public TrayIcon {
 public:
-  STrayIcon(STrayIconThread& t) : thread(t),
+  STrayIcon(STrayIconThread& t) :
     vncConfig(_T("vncconfig.exe"), isServiceProcess() ? _T("-noconsole -service") : _T("-noconsole")),
-    vncConnect(_T("winvnc4.exe"), _T("-noconsole -connect")) {
+    vncConnect(_T("winvnc4.exe"), _T("-noconsole -connect")), thread(t) {
 
     // ***
     SetWindowText(getHandle(), _T("winvnc::IPC_Interface"));
@@ -179,7 +179,7 @@
         case 2:
           return thread.server.disconnectClients("IPC disconnect") ? 1 : 0;
         case 3:
-          thread.server.setClientsStatus((rfb::ListConnInfo *)command->cbData);
+          thread.server.setClientsStatus((rfb::ListConnInfo *)command->lpData);
         case 4:
           thread.server.getClientsInfo(&LCInfo);
           CPanel->UpdateListView(&LCInfo);
@@ -231,9 +231,10 @@
 
 STrayIconThread::STrayIconThread(VNCServerWin32& sm, UINT inactiveIcon_, UINT activeIcon_, 
                                  UINT dis_inactiveIcon_, UINT dis_activeIcon_, UINT menu_)
-: Thread("TrayIcon"), server(sm), inactiveIcon(inactiveIcon_), activeIcon(activeIcon_),
-  dis_inactiveIcon(dis_inactiveIcon_), dis_activeIcon(dis_activeIcon_),menu(menu_),
-  windowHandle(0), runTrayIcon(true) {
+: Thread("TrayIcon"), windowHandle(0), server(sm),
+  inactiveIcon(inactiveIcon_), activeIcon(activeIcon_),
+  dis_inactiveIcon(dis_inactiveIcon_), dis_activeIcon(dis_activeIcon_),
+  menu(menu_), runTrayIcon(true) {
   start();
 }
 
diff --git a/win/winvnc/VNCServerService.cxx b/win/winvnc/VNCServerService.cxx
index 1a2a8e9..481df21 100644
--- a/win/winvnc/VNCServerService.cxx
+++ b/win/winvnc/VNCServerService.cxx
@@ -97,9 +97,8 @@
     if (GetSessionUserTokenWin(&hToken))
     {
         ModuleFileName filename;
-        static const char cmdLineFmt[] = "\"%s\" -noconsole -service_run";
-        TCharArray cmdLine(_tcslen(filename.buf) + sizeof(cmdLineFmt)/sizeof(cmdLineFmt[0]));
-        _stprintf(cmdLine.buf, cmdLineFmt, filename.buf);
+        TCharArray cmdLine;
+        cmdLine.format("\"%s\" -noconsole -service_run", filename.buf);
         STARTUPINFO si;
         ZeroMemory(&si, sizeof si);
         si.cb = sizeof si;
diff --git a/win/winvnc/VNCServerWin32.cxx b/win/winvnc/VNCServerWin32.cxx
index 9d77c27..36dbcee 100644
--- a/win/winvnc/VNCServerWin32.cxx
+++ b/win/winvnc/VNCServerWin32.cxx
@@ -59,8 +59,8 @@
       CreateEvent(0, FALSE, FALSE, "Global\\SessionEventTigerVNC") : 0),
     vncServer(CStr(ComputerName().buf), &desktop),
     hostThread(0), runServer(false), isDesktopStarted(false),
-    httpServer(&vncServer), config(&sockMgr), trayIcon(0),
-    rfbSock(&sockMgr), httpSock(&sockMgr),
+    httpServer(&vncServer), config(&sockMgr),
+    rfbSock(&sockMgr), httpSock(&sockMgr), trayIcon(0),
     queryConnectDialog(0)
 {
   // Initialise the desktop
@@ -189,10 +189,10 @@
 
     vlog.debug("Server exited cleanly");
   } catch (rdr::SystemException &s) {
-    vlog.error(s.str());
+    vlog.error("%s", s.str());
     result = s.err;
   } catch (rdr::Exception &e) {
-    vlog.error(e.str());
+    vlog.error("%s", e.str());
   }
 
   { Lock l(runLock);
diff --git a/win/winvnc/winvnc.cxx b/win/winvnc/winvnc.cxx
index 17b3a91..b906865 100644
--- a/win/winvnc/winvnc.cxx
+++ b/win/winvnc/winvnc.cxx
@@ -87,7 +87,7 @@
   } else {
     if (isError) {
       try {
-        vlog.error(msg);
+        vlog.error("%s", msg);
         return;
       } catch (...) {
       }
@@ -148,11 +148,11 @@
       } else if (strcasecmp(argv[i], "-status") == 0) {
         printf("Querying service status...\n");
         runServer = false;
+        CharArray result;
         DWORD state = rfb::win32::getServiceState(VNCServerService::Name);
-        CharArray stateStr(rfb::win32::serviceStateName(state));
-        const char* stateMsg = "The %s Service is in the %s state.";
-        CharArray result(strlen(stateStr.buf) + _tcslen(VNCServerService::Name) + strlen(stateMsg) + 1);
-        sprintf(result.buf, stateMsg, (const char*)CStr(VNCServerService::Name), stateStr.buf);
+        result.format("The %s Service is in the %s state.",
+                      (const char*)CStr(VNCServerService::Name),
+                      rfb::win32::serviceStateName(state));
         MsgBoxOrLog(result.buf);
       } else if (strcasecmp(argv[i], "-service") == 0) {
         printf("Run in service mode\n");
@@ -182,7 +182,7 @@
         close_console = true;
         vlog.info("closing console");
         if (!FreeConsole())
-          vlog.info("unable to close console:%u", GetLastError());
+          vlog.info("unable to close console:%lu", GetLastError());
 
       } else if ((strcasecmp(argv[i], "-help") == 0) ||
         (strcasecmp(argv[i], "--help") == 0) ||
diff --git a/win/wm_hooks/wm_hooks.cxx b/win/wm_hooks/wm_hooks.cxx
index 50a981e..c0350cd 100644
--- a/win/wm_hooks/wm_hooks.cxx
+++ b/win/wm_hooks/wm_hooks.cxx
@@ -204,11 +204,11 @@
     // Handle pop-up menus having items selected
 	case 485:
 		{
-			HANDLE prop = GetProp(wnd, (LPCTSTR) MAKELONG(ATOM_Popup_Selection, 0));
+			HANDLE prop = GetProp(wnd, (LPCTSTR) (intptr_t) ATOM_Popup_Selection);
       if (prop != (HANDLE) wParam) {
         NotifyWindow(wnd, 485);
 				SetProp(wnd,
-					(LPCTSTR) MAKELONG(ATOM_Popup_Selection, 0),
+					(LPCTSTR) (intptr_t) ATOM_Popup_Selection,
 					(HANDLE) wParam);
 			}
 		}