diff --git a/lib/matplotlib/backend_bases.py b/lib/matplotlib/backend_bases.py
index b3d4403..64848c2 100644
--- a/lib/matplotlib/backend_bases.py
+++ b/lib/matplotlib/backend_bases.py
@@ -1176,8 +1176,7 @@ class LocationEvent(Event):
             self._update_enter_leave()
             return
         elif (len(axes_list) > 1): # Overlap, get the highest zorder
-            axCmp = lambda _x,_y: cmp(_x.zorder, _y.zorder)
-            axes_list.sort(axCmp)
+            axes_list.sort(key=lambda x: x.zorder)
             self.inaxes = axes_list[-1] # Use the highest zorder
         else: # Just found one hit
             self.inaxes = axes_list[0]
diff --git a/lib/matplotlib/cbook.py b/lib/matplotlib/cbook.py
index 9b7087d..c23d0f1 100644
--- a/lib/matplotlib/cbook.py
+++ b/lib/matplotlib/cbook.py
@@ -3,6 +3,7 @@ A collection of utility functions and classes.  Many (but not all)
 from the Python Cookbook -- hence the name cbook
 """
 from __future__ import print_function
+
 import re, os, errno, sys, io, traceback, locale, threading, types
 import time, datetime
 import warnings
@@ -14,15 +15,24 @@ import os.path
 import random
 import urllib2
 from functools import reduce
-if sys.version_info[0] >= 3:
+
+major, minor1, minor2, s, tmp = sys.version_info
+
+if major >= 3:
     import types
+    import urllib.request
+    def addinfourl(data, headers, url, code=None):
+        return urllib.request.addinfourl(io.BytesIO(data),
+                                         headers, url, code)
 else:
     import new
+    import urllib2
+    def addinfourl(data, headers, url, code=None):
+        return urllib2.addinfourl(io.StringIO(data),
+                                  headers, url, code)
 
 import matplotlib
 
-major, minor1, minor2, s, tmp = sys.version_info
-
 
 # On some systems, locale.getpreferredencoding returns None,
 # which can break unicode; and the sage project reports that
@@ -275,7 +285,7 @@ class CallbackRegistry:
         callbacks on *s* will be called with *\*args* and *\*\*kwargs*
         """
         self._check_signal(s)
-        for cid, proxy in self.callbacks[s].iteritems():
+        for cid, proxy in self.callbacks[s].items():
             # Clean out dead references
             if proxy.inst is not None and proxy.inst() is None:
                 del self.callbacks[s][cid]
@@ -571,7 +581,8 @@ class ViewVCCachedServer(urllib2.HTTPSHandler):
         if url in self.cache:
             _, etag, lastmod = self.cache[url]
             req.add_header("If-None-Match", etag)
-            req.add_header("If-Modified-Since", lastmod)
+            if lastmod:
+                req.add_header("If-Modified-Since", lastmod)
         return req
 
     def https_error_304(self, req, fp, code, msg, hdrs):
@@ -584,7 +595,7 @@ class ViewVCCachedServer(urllib2.HTTPSHandler):
             'ViewVCCachedServer: reading data file from cache file "%s"' %fn,
             'debug')
         file = open(fn, 'rb')
-        handle = urllib2.addinfourl(file, hdrs, url)
+        handle = addinfourl(file, hdrs, url)
         handle.code = 304
         return handle
 
@@ -599,9 +610,7 @@ class ViewVCCachedServer(urllib2.HTTPSHandler):
         else:
             data = response.read()
             self.cache_file(req.get_full_url(), data, response.headers)
-            result = urllib2.addinfourl(io.StringIO(data),
-                                        response.headers,
-                                        req.get_full_url())
+            result = addinfourl(data, response.headers, req.get_full_url())
             result.code = response.code
             result.msg = response.msg
             return result
@@ -620,10 +629,7 @@ class ViewVCCachedServer(urllib2.HTTPSHandler):
 
         # quote is not in python2.4, so check for it and get it from
         # urllib if it is not available
-        quote = getattr(urllib2, 'quote', None)
-        if quote is None:
-            import urllib
-            quote = urllib.quote
+        quote = urllib2.quote
 
         # retrieve the URL for the side effect of refreshing the cache
         url = self.baseurl + quote(fname)
diff --git a/lib/matplotlib/contour.py b/lib/matplotlib/contour.py
index ecf33d4..96ce5e3 100644
--- a/lib/matplotlib/contour.py
+++ b/lib/matplotlib/contour.py
@@ -12,7 +12,7 @@ import matplotlib.path as mpath
 import matplotlib.ticker as ticker
 import matplotlib.cm as cm
 import matplotlib.colors as colors
-import matplotlib.collections as collections
+import matplotlib.collections as mcoll
 import matplotlib.font_manager as font_manager
 import matplotlib.text as text
 import matplotlib.cbook as cbook
@@ -703,9 +703,9 @@ class ContourSet(cm.ScalarMappable, ContourLabeler):
                 ncolors -= 1
             cmap = colors.ListedColormap(self.colors, N=ncolors)
         if self.filled:
-            self.collections = cbook.silent_list('collections.PathCollection')
+            self.collections = cbook.silent_list('mcoll.PathCollection')
         else:
-            self.collections = cbook.silent_list('collections.LineCollection')
+            self.collections = cbook.silent_list('mcoll.LineCollection')
         # label lists must be initialized here
         self.labelTexts = []
         self.labelCValues = []
@@ -734,7 +734,7 @@ class ContourSet(cm.ScalarMappable, ContourLabeler):
                 paths = self._make_paths(segs, kinds)
                 # Default zorder taken from Collection
                 zorder = kwargs.get('zorder', 1)
-                col = collections.PathCollection(paths,
+                col = mcoll.PathCollection(paths,
                                      antialiaseds = (self.antialiased,),
                                      edgecolors= 'none',
                                      alpha=self.alpha,
@@ -752,7 +752,7 @@ class ContourSet(cm.ScalarMappable, ContourLabeler):
                     zip(self.levels, tlinewidths, tlinestyles, self.allsegs):
                 # Default zorder taken from LineCollection
                 zorder = kwargs.get('zorder', 2)
-                col = collections.LineCollection(segs,
+                col = mcoll.LineCollection(segs,
                                      antialiaseds = aa,
                                      linewidths = width,
                                      linestyle = lstyle,
diff --git a/lib/matplotlib/delaunay/_delaunay.cpp b/lib/matplotlib/delaunay/_delaunay.cpp
index c51e825..074ca13 100644
--- a/lib/matplotlib/delaunay/_delaunay.cpp
+++ b/lib/matplotlib/delaunay/_delaunay.cpp
@@ -727,7 +727,7 @@ static PyMethodDef delaunay_methods[] = {
 };
 
 #if PY_MAJOR_VERSION >= 3
-static PyModuleDef delaunay_module = {
+static struct PyModuleDef delaunay_module = {
     PyModuleDef_HEAD_INIT,
     "_delaunay",
     "Tools for computing the Delaunay triangulation and some operations on it.\n",
@@ -740,7 +740,7 @@ PyMODINIT_FUNC
 PyInit__delaunay(void)
 {
     PyObject* m;
-    // import_array():
+    import_array();
 
     m = PyModule_Create(&delaunay_module);
     if (m == NULL)
diff --git a/lib/matplotlib/finance.py b/lib/matplotlib/finance.py
index b11d349..66a6cbd 100644
--- a/lib/matplotlib/finance.py
+++ b/lib/matplotlib/finance.py
@@ -4,13 +4,15 @@ financial data.   User contributions welcome!
 
 """
 #from __future__ import division
-import os, warnings
+import sys, os, warnings
 from urllib2 import urlopen
 
-try:
+if sys.version_info[0] < 3:
     from hashlib import md5
-except ImportError:
-    from md5 import md5 #Deprecated in 2.5
+else:
+    import hashlib
+    md5 = lambda x: hashlib.md5(x.encode())
+
 import datetime
 
 import numpy as np
@@ -177,7 +179,7 @@ def fetch_historical_yahoo(ticker, date1, date2, cachename=None):
             os.mkdir(cachedir)
         urlfh = urlopen(url)
 
-        fh = open(cachename, 'w')
+        fh = open(cachename, 'wb')
         fh.write(urlfh.read())
         fh.close()
         verbose.report('Saved %s data to cache file %s'%(ticker, cachename))
diff --git a/lib/matplotlib/tri/_tri.cpp b/lib/matplotlib/tri/_tri.cpp
index 9b0b24c..7d8358d 100644
--- a/lib/matplotlib/tri/_tri.cpp
+++ b/lib/matplotlib/tri/_tri.cpp
@@ -988,9 +988,10 @@ PyMODINIT_FUNC
 init_tri(void)
 #endif
 {
+    import_array();
+
     static TriModule* triModule = NULL;
     triModule = new TriModule();
-    import_array();
 
     #if PY_MAJOR_VERSION >= 3
     return triModule->module().ptr();
diff --git a/lib/mpl_toolkits/mplot3d/art3d.py b/lib/mpl_toolkits/mplot3d/art3d.py
index a355dd3..1a24cf5 100644
--- a/lib/mpl_toolkits/mplot3d/art3d.py
+++ b/lib/mpl_toolkits/mplot3d/art3d.py
@@ -439,7 +439,7 @@ class Poly3DCollection(PolyCollection):
         if self._zsort:
             z_segments_2d = [(self._zsortfunc(zs), zip(xs, ys), fc, ec) for
                     (xs, ys, zs), fc, ec in zip(xyzlist, cface, cedge)]
-            z_segments_2d.sort(cmp=lambda x, y: cmp(y[0], x[0]))
+            z_segments_2d.sort(key=lambda x: x[0], reverse=True)
         else:
             raise ValueError, "whoops"
 
diff --git a/setupext.py b/setupext.py
index d787f42..51ea84e 100644
--- a/setupext.py
+++ b/setupext.py
@@ -928,7 +928,7 @@ def add_tk_flags(module):
     message = None
     if sys.platform == 'win32':
         major, minor1, minor2, s, tmp = sys.version_info
-        if major == 2 and minor1 in [6, 7]:
+        if (2, 6) <= (major, minor1) <= (3, 2):
             module.include_dirs.extend(['win32_static/include/tcl85'])
             module.libraries.extend(['tk85', 'tcl85'])
         elif major == 2 and minor1 in [3, 4, 5]:
diff --git a/src/_tkagg.cpp b/src/_tkagg.cpp
index 31b9ad6..1f3972f 100644
--- a/src/_tkagg.cpp
+++ b/src/_tkagg.cpp
@@ -34,7 +34,11 @@ extern "C"
 #endif
 }
 
-
+#if defined(_MSC_VER)
+#  define SIZE_T_FORMAT "%Iu"
+#else
+#  define SIZE_T_FORMAT "%zu"
+#endif
 
 typedef struct
 {
@@ -53,7 +57,7 @@ PyAggImagePhoto(ClientData clientdata, Tcl_Interp* interp,
     // vars for blitting
     PyObject* bboxo;
 
-    unsigned long aggl, bboxl;
+    size_t aggl, bboxl;
     bool has_bbox;
     agg::int8u *destbuffer;
     double l, b, r, t;
@@ -83,7 +87,7 @@ PyAggImagePhoto(ClientData clientdata, Tcl_Interp* interp,
         return TCL_ERROR;
     }
     /* get array (or object that can be converted to array) pointer */
-    if (sscanf(argv[2], "%lu", &aggl) != 1)
+    if (sscanf(argv[2], SIZE_T_FORMAT, &aggl) != 1)
     {
         Tcl_AppendResult(interp, "error casting pointer", (char *) NULL);
         return TCL_ERROR;
@@ -109,7 +113,7 @@ PyAggImagePhoto(ClientData clientdata, Tcl_Interp* interp,
     }
 
     /* check for bbox/blitting */
-    if (sscanf(argv[4], "%lu", &bboxl) != 1)
+    if (sscanf(argv[4], SIZE_T_FORMAT, &bboxl) != 1)
     {
         Tcl_AppendResult(interp, "error casting pointer", (char *) NULL);
         return TCL_ERROR;
@@ -261,6 +265,7 @@ static PyMethodDef functions[] =
     {NULL, NULL} /* sentinel */
 };
 
+extern "C"
 #if PY3K
 static PyModuleDef _tkagg_module = {
     PyModuleDef_HEAD_INIT,
@@ -277,12 +282,13 @@ PyInit__tkagg(void)
     PyObject* m;
 
     m = PyModule_Create(&_tkagg_module);
+    
+    import_array();
 
     return m;
 }
 #else
-extern "C"
-    DL_EXPORT(void) init_tkagg(void)
+PyMODINIT_FUNC init_tkagg(void)
 {
     import_array();
 
diff --git a/src/_windowing.cpp b/src/_windowing.cpp
index 949944c..7a20baa 100644
--- a/src/_windowing.cpp
+++ b/src/_windowing.cpp
@@ -1,5 +1,3 @@
-/* -*- mode: c++; c-basic-offset: 4 -*- */
-
 #include "Python.h"
 #include <windows.h>
 
@@ -11,14 +9,14 @@ _GetForegroundWindow(PyObject *module, PyObject *args)
     {
         return NULL;
     }
-    return PyInt_FromLong((long) handle);
+    return PyLong_FromSize_t((size_t)handle);
 }
 
 static PyObject *
 _SetForegroundWindow(PyObject *module, PyObject *args)
 {
     HWND handle;
-    if (!PyArg_ParseTuple(args, "l:SetForegroundWindow", &handle))
+    if (!PyArg_ParseTuple(args, "n:SetForegroundWindow", &handle))
     {
         return NULL;
     }
@@ -38,7 +36,29 @@ static PyMethodDef _windowing_methods[] =
     {NULL, NULL}
 };
 
-extern "C" DL_EXPORT(void) init_windowing()
+#if PY_MAJOR_VERSION >= 3
+
+static struct PyModuleDef moduledef = {
+        PyModuleDef_HEAD_INIT,
+        "_windowing",
+        "",
+        -1,
+        _windowing_methods,
+        NULL,
+        NULL,
+        NULL,
+        NULL
+};
+
+PyMODINIT_FUNC PyInit__windowing(void)
+{
+    PyObject *module = PyModule_Create(&moduledef);
+    return module;
+}
+
+#else
+PyMODINIT_FUNC init_windowing()
 {
     Py_InitModule("_windowing", _windowing_methods);
 }
+#endif
diff --git a/src/ft2font.cpp b/src/ft2font.cpp
index 52037bc..2faf4c8 100644
--- a/src/ft2font.cpp
+++ b/src/ft2font.cpp
@@ -6,8 +6,8 @@
 
 #include "numpy/arrayobject.h"
 
-#define FIXED_MAJOR(val) (*((unsigned long*) &val+1))
-#define FIXED_MINOR(val) (*((unsigned long*) &val+0))
+#define FIXED_MAJOR(val) (*((short *) &val+1))
+#define FIXED_MINOR(val) (*((short *) &val+0))
 
 /**
  To improve the hinting of the fonts, this code uses a hack
@@ -2182,14 +2182,7 @@ ft2font_module::~ft2font_module()
     FT_Done_FreeType(_ft2Library);
 }
 
-#if defined(_MSC_VER)
-DL_EXPORT(void)
-#elif defined(__cplusplus)
 extern "C"
-#else
-void
-#endif
-
 #if PY3K
 PyMODINIT_FUNC
 PyInit_ft2font(void)
