Index: docker/build-mlxwinebuild.sh
===================================================================
--- docker/build-mlxwinebuild.sh	(revision 939)
+++ docker/build-mlxwinebuild.sh	(revision 939)
@@ -0,0 +1,9 @@
+#!/bin/bash
+
+set -e -u
+
+sdistfile="${1}"
+sdistdir=$(cd $(dirname "${sdistfile}") && pwd)
+
+docker run --rm -v "${sdistdir}:/root/dist" mlxwinebuild-py3 build $(basename "${sdistfile}") $(id -u) $(id -g)
+#docker run -it --rm -v "${sdistdir}:/root/dist" mlxwinebuild-py3 bash
Index: docker/build-mlxwinebuild.sh
===================================================================
--- docker/build-mlxwinebuild.sh	(revision 916)
+++ 	(revision )
@@ -1,9 +1,0 @@
-#!/bin/bash
-
-set -e -u
-
-sdistfile="${1}"
-sdistdir=$(cd $(dirname "${sdistfile}") && pwd)
-
-docker run --rm -v "${sdistdir}:/root/dist" mlxwinebuild build $(basename "${sdistfile}") $(id -u) $(id -g)
-#docker run -it --rm -v "${sdistdir}:/root/dist" mlxwinebuild bash
Index: docker/context/Dockerfile
===================================================================
--- docker/context/Dockerfile	(revision 939)
+++ docker/context/Dockerfile	(revision 939)
@@ -0,0 +1,18 @@
+FROM ubuntu:cosmic
+
+RUN dpkg --add-architecture i386 && \
+    apt-get update -y && \
+    /usr/bin/env DEBIAN_FRONTEND=noninteractive apt-get install -y \
+        tzdata \
+        wget \
+        wine \
+        wine32 && \
+    apt-get clean && \
+    echo "Europe/Budapest" > /etc/timezone && \
+    rm -f /etc/localtime && \
+    dpkg-reconfigure -f noninteractive tzdata
+
+ADD entrypoint.sh setup.sh build.sh /root/
+
+ENTRYPOINT ["/root/entrypoint.sh"]
+CMD ["bash"]
Index: docker/context/Dockerfile
===================================================================
--- docker/context/Dockerfile	(revision 916)
+++ 	(revision )
@@ -1,17 +1,0 @@
-FROM ubuntu:cosmic
-
-RUN dpkg --add-architecture i386 && \
-    apt-get update -y && \
-    /usr/bin/env DEBIAN_FRONTEND=noninteractive apt-get install -y \
-        tzdata \
-        wget \
-        wine \
-        wine32 && \
-    echo "Europe/Budapest" > /etc/timezone && \
-    rm -f /etc/localtime && \
-    dpkg-reconfigure -f noninteractive tzdata
-
-ADD entrypoint.sh setup.sh build.sh /root/
-
-ENTRYPOINT ["/root/entrypoint.sh"]
-CMD ["bash"]
Index: docker/context/build.sh
===================================================================
--- docker/context/build.sh	(revision 939)
+++ docker/context/build.sh	(revision 939)
@@ -0,0 +1,38 @@
+#!/bin/bash
+
+set -e -u
+
+scriptdir=$(cd $(dirname $0) && pwd)
+
+sdistname="${1}"
+uid="${2}"
+gid="${3}"
+
+mlxdirname=$(basename "${sdistname}" .tar.gz)
+version=$(echo "${mlxdirname}" | sed "s:mlx-::")
+
+cd "${scriptdir}"
+
+tar xf "dist/${sdistname}"
+
+cd "${mlxdirname}"
+
+export WINE=yes
+./makeinst.sh
+
+echo
+echo "Copying the 'dist' directory..."
+destdistdir="../dist/dist-${version}"
+
+rm -rf "${destdistdir}"
+cp -a dist "${destdistdir}"
+chown -R ${uid}:${gid} "${destdistdir}"
+
+echo
+echo "Copying the setup program..."
+
+cp "MAVA Logger X-${version}-Setup.exe" ../dist
+chown ${uid}:${gid} "../dist/MAVA Logger X-${version}-Setup.exe"
+
+echo
+echo "Done."
Index: docker/context/build.sh
===================================================================
--- docker/context/build.sh	(revision 916)
+++ 	(revision )
@@ -1,37 +1,0 @@
-#!/bin/bash
-
-set -e -u
-
-scriptdir=$(cd $(dirname $0) && pwd)
-
-sdistname="${1}"
-uid="${2}"
-gid="${3}"
-
-mlxdirname=$(basename "${sdistname}" .tar.gz)
-version=$(echo "${mlxdirname}" | sed "s:mlx-::")
-
-cd "${scriptdir}"
-
-tar xf "dist/${sdistname}"
-
-cd "${mlxdirname}"
-
-echo "winemakeinst.bat" | wine cmd
-
-echo
-echo "Copying the 'dist' directory..."
-destdistdir="../dist/dist-${version}"
-
-rm -rf "${destdistdir}"
-cp -a dist "${destdistdir}"
-chown -R ${uid}:${gid} "${destdistdir}"
-
-echo
-echo "Copying the setup program..."
-
-cp "MAVA Logger X-${version}-Setup.exe" ../dist
-chown ${uid}:${gid} "../dist/MAVA Logger X-${version}-Setup.exe"
-
-echo
-echo "Done."
Index: docker/context/entrypoint.sh
===================================================================
--- docker/context/entrypoint.sh	(revision 916)
+++ docker/context/entrypoint.sh	(revision 916)
@@ -0,0 +1,12 @@
+#!/bin/bash
+
+scriptdir=$(cd $(dirname $0) && pwd)
+
+if test "$1" = "initialize"; then
+    "${scriptdir}/setup.sh"
+elif test "$1" = "build"; then
+    shift
+    "${scriptdir}/build.sh" "$@"
+else
+    exec "$@"
+fi
Index: docker/context/entrypoint.sh
===================================================================
--- docker/context/entrypoint.sh	(revision 916)
+++ 	(revision )
@@ -1,12 +1,0 @@
-#!/bin/bash
-
-scriptdir=$(cd $(dirname $0) && pwd)
-
-if test "$1" = "initialize"; then
-    "${scriptdir}/setup.sh"
-elif test "$1" = "build"; then
-    shift
-    "${scriptdir}/build.sh" "$@"
-else
-    exec "$@"
-fi
Index: docker/context/setup.sh
===================================================================
--- docker/context/setup.sh	(revision 939)
+++ docker/context/setup.sh	(revision 939)
@@ -0,0 +1,36 @@
+#!/bin/bash
+
+set -e -u
+
+cdrive="${HOME}/.wine/drive_c"
+cpythondir="${cdrive}/msys64/mingw32"
+
+if test -f "${cpythondir}/bin/python3.exe"; then
+    echo "Image already configured, not doing anything!"
+    exit 1
+fi
+
+echo "Preparing image to be able to build MAVA Logger X for Windows"
+echo
+
+export WINEARCH=win32
+
+echo "exit" | wine cmd
+
+echo "Downloading and extracting the extra packages..."
+
+wget -O - mlx.varadiistvan.hu/update/msys64.tar.gz | tar xzf - -C "${cdrive}"
+wget -O - mlx.varadiistvan.hu/update/winepkgs.tar | tar xf - nsis-2.46-setup.exe pyuipc-cpython-37m.dll xplra.py
+
+mv  pyuipc-cpython-37m.dll xplra.py /root/.wine/drive_c/msys64/mingw32/lib/python3.7/site-packages
+
+echo
+echo "Installing extra packages..."
+
+wine nsis-2.46-setup.exe
+
+echo
+echo "Removing extra packages..."
+rm -f *.exe
+echo
+echo "Done."
Index: docker/context/setup.sh
===================================================================
--- docker/context/setup.sh	(revision 916)
+++ 	(revision )
@@ -1,52 +1,0 @@
-#!/bin/bash
-
-set -e -u
-
-cdrive="${HOME}/.wine/drive_c"
-ctmpdir="${cdrive}/tmp"
-cpythondir="${cdrive}/Python27"
-cwinsysdir="${cdrive}/windows/system32"
-
-if test -f "${cpythondir}/python.exe"; then
-    echo "Image already configured, not doing anything!"
-    exit 1
-fi
-
-echo "Preparing image to be able to build MAVA Logger X for Windows"
-echo
-
-echo "Downloading and extracting the extra packages..."
-
-wget -O - mlx.varadiistvan.hu/update/winepkgs.tar | tar xf -
-
-echo
-echo "Installing extra packages..."
-
-export WINEARCH=win32
-
-echo "exit" | wine cmd
-wine msiexec /i python-2.7.2.msi
-wine msiexec /i cefpython3-31.2.py2.7-win32.msi
-wine msiexec /i pygtk-all-in-one-2.24.1.win32-py2.7.msi
-wine msiexec /i pyuipc-0.4.win32-py2.7.msi
-wine msiexec /i xplra-0.2.win32.msi
-
-wine pywin32-217.win32-py2.7.exe
-wine py2exe-0.6.9.win32-py2.7.exe
-wine nsis-2.46-setup.exe
-
-mkdir "${ctmpdir}"
-cp chromedriver.exe "${ctmpdir}"
-
-tar xzf Python27.extra.tar.gz -C "${cpythondir}"
-
-touch -d "2015-02-22 14:50:07" "${cpythondir}/Lib/site-packages/win32/lib/win32con.py"
-touch -d "2015-02-22 14:50:07" "${cpythondir}/Lib/site-packages/win32/lib/winerror.py"
-
-cp python27.dll WINHTTP.dll "${cwinsysdir}"
-
-echo
-echo "Removing extra packages..."
-rm -f *.msi *.exe Python27.extra.tar.gz python27.dll WINHTTP.dll
-echo
-echo "Done."
Index: docker/initialize-mlxwinebuild.sh
===================================================================
--- docker/initialize-mlxwinebuild.sh	(revision 939)
+++ docker/initialize-mlxwinebuild.sh	(revision 939)
@@ -0,0 +1,23 @@
+#!/bin/bash
+
+set -e -u
+
+scriptdir=`dirname $0`
+scriptdir=`cd "${scriptdir}" && pwd`
+
+docker build -t mlxwinebuild-py3-base "${scriptdir}/context"
+
+if test -z "${XAUTHORITY:-}"; then
+    XAUTHORITY="${HOME}/.Xauthority"
+fi
+
+docker run -it --name mlxwinebuildinit -v /tmp/.X11-unix:/tmp/.X11-unix -v "${XAUTHORITY}":/root/.Xauthority -v /usr/lib/x86_64-linux-gnu/vdpau:/usr/lib/x86_64-linux-gnu/vdpau --device /dev/nvidiactl --device /dev/nvidia0 --security-opt=apparmor:unconfined  --env DISPLAY mlxwinebuild-py3-base initialize
+
+echo "Committing new image..."
+
+docker commit --change='CMD ["bash"]' mlxwinebuildinit mlxwinebuild-py3
+
+echo "Removing container..."
+docker rm mlxwinebuildinit
+
+echo "Done."
Index: docker/initialize-mlxwinebuild.sh
===================================================================
--- docker/initialize-mlxwinebuild.sh	(revision 916)
+++ 	(revision )
@@ -1,23 +1,0 @@
-#!/bin/bash
-
-set -e -u
-
-scriptdir=`dirname $0`
-scriptdir=`cd "${scriptdir}" && pwd`
-
-docker build -t mlxwinebuild-base "${scriptdir}/context"
-
-if test -z "${XAUTHORITY:-}"; then
-    XAUTHORITY="${HOME}/.Xauthority"
-fi
-
-docker run -it --name mlxwinebuildinit -v /tmp/.X11-unix:/tmp/.X11-unix -v "${XAUTHORITY}":/root/.Xauthority -v /usr/lib/x86_64-linux-gnu/vdpau:/usr/lib/x86_64-linux-gnu/vdpau --device /dev/nvidiactl --device /dev/nvidia0 --security-opt=apparmor:unconfined  --env DISPLAY mlxwinebuild-base initialize
-
-echo "Committing new image..."
-
-docker commit --change='CMD ["bash"]' mlxwinebuildinit mlxwinebuild
-
-echo "Removing container..."
-docker rm mlxwinebuildinit
-
-echo "Done."
Index: docker/msys/Dockerfile
===================================================================
--- docker/msys/Dockerfile	(revision 920)
+++ docker/msys/Dockerfile	(revision 920)
@@ -0,0 +1,25 @@
+#escape=`
+FROM mcr.microsoft.com/windows/servercore:1809
+SHELL ["powershell", "-Command"]
+
+RUN $WebClient = New-Object System.Net.WebClient ; `
+    $WebClient.DownloadFile('https://www.7-zip.org/a/7z1900-x64.msi', '7z.msi') ; `
+    $WebClient.DownloadFile('http://repo.msys2.org/distrib/msys2-x86_64-latest.tar.xz', 'msys2.tar.xz') ; `
+    Start-Process msiexec.exe -ArgumentList '/i C:\7z.msi /qn reboot=r' -Wait -PassThru -Verbose ; `
+    Start-Process 'C:\Program Files\7-Zip\7z.exe' -ArgumentList 'x msys2.tar.xz' -Wait -PassThru -Verbose ; `
+    Start-Process tar -ArgumentList 'xf msys2.tar' -Wait -PassThru -Verbose ; `
+    Start-Process msiexec.exe -ArgumentList '/x C:\7z.msi /qn reboot=r' -Wait -PassThru -Verbose ; `
+    Remove-Item msys2.tar ; `
+    Remove-Item msys2.tar.xz ; `
+    Remove-Item 7z.msi
+
+RUN $env:MSYSTEM='MINGW32' ; `
+    Start-Process C:\msys64\usr\bin\pacman.exe -ArgumentList '-Syu --noconfirm' -Wait -PassThru -Verbose -WorkingDirectory 'C:\msys64' ; `
+    Start-Process C:\msys64\usr\bin\pacman.exe -ArgumentList '-Su --noconfirm' -Wait -PassThru -Verbose -WorkingDirectory 'C:\msys64' ; `
+    Start-Process C:\msys64\usr\bin\bash.exe -ArgumentList '--login -c /usr/bin/true.exe' -Wait -PassThru -Verbose -WorkingDirectory 'C:\msys64'; `
+    mkdir C:\msys64\build
+
+COPY setup.sh pywin32.patch pywin32git.patch cef_binary_3.3359.1774.gd49d25f_windows32.patch cefpython-66.0.patch py2exe.patch C:\msys64\build\
+
+RUN $env:MSYSTEM='MINGW32'; `
+    C:\msys64\usr\bin\bash.exe --login  C:\msys64\build\setup.sh ;
Index: docker/msys/Dockerfile
===================================================================
--- docker/msys/Dockerfile	(revision 920)
+++ 	(revision )
@@ -1,25 +1,0 @@
-#escape=`
-FROM mcr.microsoft.com/windows/servercore:1809
-SHELL ["powershell", "-Command"]
-
-RUN $WebClient = New-Object System.Net.WebClient ; `
-    $WebClient.DownloadFile('https://www.7-zip.org/a/7z1900-x64.msi', '7z.msi') ; `
-    $WebClient.DownloadFile('http://repo.msys2.org/distrib/msys2-x86_64-latest.tar.xz', 'msys2.tar.xz') ; `
-    Start-Process msiexec.exe -ArgumentList '/i C:\7z.msi /qn reboot=r' -Wait -PassThru -Verbose ; `
-    Start-Process 'C:\Program Files\7-Zip\7z.exe' -ArgumentList 'x msys2.tar.xz' -Wait -PassThru -Verbose ; `
-    Start-Process tar -ArgumentList 'xf msys2.tar' -Wait -PassThru -Verbose ; `
-    Start-Process msiexec.exe -ArgumentList '/x C:\7z.msi /qn reboot=r' -Wait -PassThru -Verbose ; `
-    Remove-Item msys2.tar ; `
-    Remove-Item msys2.tar.xz ; `
-    Remove-Item 7z.msi
-
-RUN $env:MSYSTEM='MINGW32' ; `
-    Start-Process C:\msys64\usr\bin\pacman.exe -ArgumentList '-Syu --noconfirm' -Wait -PassThru -Verbose -WorkingDirectory 'C:\msys64' ; `
-    Start-Process C:\msys64\usr\bin\pacman.exe -ArgumentList '-Su --noconfirm' -Wait -PassThru -Verbose -WorkingDirectory 'C:\msys64' ; `
-    Start-Process C:\msys64\usr\bin\bash.exe -ArgumentList '--login -c /usr/bin/true.exe' -Wait -PassThru -Verbose -WorkingDirectory 'C:\msys64'; `
-    mkdir C:\msys64\build
-
-COPY setup.sh pywin32.patch pywin32git.patch cef_binary_3.3359.1774.gd49d25f_windows32.patch cefpython-66.0.patch py2exe.patch C:\msys64\build\
-
-RUN $env:MSYSTEM='MINGW32'; `
-    C:\msys64\usr\bin\bash.exe --login  C:\msys64\build\setup.sh ;
Index: docker/msys/cef_binary_3.3359.1774.gd49d25f_windows32.patch
===================================================================
--- docker/msys/cef_binary_3.3359.1774.gd49d25f_windows32.patch	(revision 920)
+++ docker/msys/cef_binary_3.3359.1774.gd49d25f_windows32.patch	(revision 920)
@@ -0,0 +1,367 @@
+--- cef_binary_3.3359.1774.gd49d25f_windows32/include/internal/cef_string_wrappers.h.orig	2019-03-09 15:59:59.571378000 +0100
++++ cef_binary_3.3359.1774.gd49d25f_windows32/include/internal/cef_string_wrappers.h	2019-03-09 16:00:08.284090000 +0100
+@@ -33,6 +33,7 @@
+ 
+ #include <memory.h>
+ #include <string>
++#include <cstring>
+ 
+ #include "include/base/cef_string16.h"
+ #include "include/internal/cef_string_types.h"
+--- cef_binary_3.3359.1774.gd49d25f_windows32/include/base/cef_bind_helpers.h.orig	2018-05-17 11:46:05.000000000 +0200
++++ cef_binary_3.3359.1774.gd49d25f_windows32/include/base/cef_bind_helpers.h	2019-03-09 16:03:17.830725000 +0100
+@@ -272,12 +272,12 @@
+ // MSVC warns when you try to use Base if T has a private destructor, the
+ // common pattern for refcounted types. It does this even though no attempt to
+ // instantiate Base is made.  We disable the warning for this definition.
+-#if defined(OS_WIN)
++#if defined(OS_WIN) && defined(COMPILER_MSVC)
+ #pragma warning(push)
+ #pragma warning(disable : 4624)
+ #endif
+   struct Base : public T, public BaseMixin {};
+-#if defined(OS_WIN)
++#if defined(OS_WIN) && defined(COMPILER_MSVC)
+ #pragma warning(pop)
+ #endif
+ 
+--- cef_binary_3.3359.1774.gd49d25f_windows32/include/base/internal/cef_atomicops_x86_gcc.h.orig	2019-04-02 20:09:10.287478919 +0200
++++ cef_binary_3.3359.1774.gd49d25f_windows32/include/base/internal/cef_atomicops_x86_gcc.h	2019-04-02 20:09:10.287478919 +0200
+@@ -0,0 +1,268 @@
++// Copyright (c) 2011 Google Inc. All rights reserved.
++//
++// Redistribution and use in source and binary forms, with or without
++// modification, are permitted provided that the following conditions are
++// met:
++//
++//    * Redistributions of source code must retain the above copyright
++// notice, this list of conditions and the following disclaimer.
++//    * Redistributions in binary form must reproduce the above
++// copyright notice, this list of conditions and the following disclaimer
++// in the documentation and/or other materials provided with the
++// distribution.
++//    * Neither the name of Google Inc. nor the name Chromium Embedded
++// Framework nor the names of its contributors may be used to endorse
++// or promote products derived from this software without specific prior
++// written permission.
++//
++// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
++// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
++// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
++// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
++// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
++// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
++// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
++// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
++// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
++// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
++// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
++
++// Do not include this header file directly. Use base/cef_atomicops.h
++// instead.
++
++#ifndef CEF_INCLUDE_BASE_INTERNAL_CEF_ATOMICOPS_X86_GCC_H_
++#define CEF_INCLUDE_BASE_INTERNAL_CEF_ATOMICOPS_X86_GCC_H_
++
++// This struct is not part of the public API of this module; clients may not
++// use it.
++// Features of this x86.  Values may not be correct before main() is run,
++// but are set conservatively.
++struct AtomicOps_x86CPUFeatureStruct {
++  bool has_amd_lock_mb_bug;  // Processor has AMD memory-barrier bug; do lfence
++                             // after acquire compare-and-swap.
++};
++extern struct AtomicOps_x86CPUFeatureStruct AtomicOps_Internalx86CPUFeatures;
++
++#define ATOMICOPS_COMPILER_BARRIER() __asm__ __volatile__("" : : : "memory")
++
++namespace base {
++namespace subtle {
++
++// 32-bit low-level operations on any platform.
++
++inline Atomic32 NoBarrier_CompareAndSwap(volatile Atomic32* ptr,
++                                         Atomic32 old_value,
++                                         Atomic32 new_value) {
++  Atomic32 prev;
++  __asm__ __volatile__("lock; cmpxchgl %1,%2"
++                       : "=a"(prev)
++                       : "q"(new_value), "m"(*ptr), "0"(old_value)
++                       : "memory");
++  return prev;
++}
++
++inline Atomic32 NoBarrier_AtomicExchange(volatile Atomic32* ptr,
++                                         Atomic32 new_value) {
++  __asm__ __volatile__("xchgl %1,%0"  // The lock prefix is implicit for xchg.
++                       : "=r"(new_value)
++                       : "m"(*ptr), "0"(new_value)
++                       : "memory");
++  return new_value;  // Now it's the previous value.
++}
++
++inline Atomic32 NoBarrier_AtomicIncrement(volatile Atomic32* ptr,
++                                          Atomic32 increment) {
++  Atomic32 temp = increment;
++  __asm__ __volatile__("lock; xaddl %0,%1"
++                       : "+r"(temp), "+m"(*ptr)
++                       :
++                       : "memory");
++  // temp now holds the old value of *ptr
++  return temp + increment;
++}
++
++inline Atomic32 Barrier_AtomicIncrement(volatile Atomic32* ptr,
++                                        Atomic32 increment) {
++  Atomic32 temp = increment;
++  __asm__ __volatile__("lock; xaddl %0,%1"
++                       : "+r"(temp), "+m"(*ptr)
++                       :
++                       : "memory");
++  // temp now holds the old value of *ptr
++  if (AtomicOps_Internalx86CPUFeatures.has_amd_lock_mb_bug) {
++    __asm__ __volatile__("lfence" : : : "memory");
++  }
++  return temp + increment;
++}
++
++inline Atomic32 Acquire_CompareAndSwap(volatile Atomic32* ptr,
++                                       Atomic32 old_value,
++                                       Atomic32 new_value) {
++  Atomic32 x = NoBarrier_CompareAndSwap(ptr, old_value, new_value);
++  if (AtomicOps_Internalx86CPUFeatures.has_amd_lock_mb_bug) {
++    __asm__ __volatile__("lfence" : : : "memory");
++  }
++  return x;
++}
++
++inline Atomic32 Release_CompareAndSwap(volatile Atomic32* ptr,
++                                       Atomic32 old_value,
++                                       Atomic32 new_value) {
++  return NoBarrier_CompareAndSwap(ptr, old_value, new_value);
++}
++
++inline void NoBarrier_Store(volatile Atomic32* ptr, Atomic32 value) {
++  *ptr = value;
++}
++
++inline void MemoryBarrier() {
++  __asm__ __volatile__("mfence" : : : "memory");
++}
++
++inline void Acquire_Store(volatile Atomic32* ptr, Atomic32 value) {
++  *ptr = value;
++  MemoryBarrier();
++}
++
++inline void Release_Store(volatile Atomic32* ptr, Atomic32 value) {
++  ATOMICOPS_COMPILER_BARRIER();
++  *ptr = value;  // An x86 store acts as a release barrier.
++  // See comments in Atomic64 version of Release_Store(), below.
++}
++
++inline Atomic32 NoBarrier_Load(volatile const Atomic32* ptr) {
++  return *ptr;
++}
++
++inline Atomic32 Acquire_Load(volatile const Atomic32* ptr) {
++  Atomic32 value = *ptr;  // An x86 load acts as a acquire barrier.
++  // See comments in Atomic64 version of Release_Store(), below.
++  ATOMICOPS_COMPILER_BARRIER();
++  return value;
++}
++
++inline Atomic32 Release_Load(volatile const Atomic32* ptr) {
++  MemoryBarrier();
++  return *ptr;
++}
++
++#if defined(__x86_64__)
++
++// 64-bit low-level operations on 64-bit platform.
++
++inline Atomic64 NoBarrier_CompareAndSwap(volatile Atomic64* ptr,
++                                         Atomic64 old_value,
++                                         Atomic64 new_value) {
++  Atomic64 prev;
++  __asm__ __volatile__("lock; cmpxchgq %1,%2"
++                       : "=a"(prev)
++                       : "q"(new_value), "m"(*ptr), "0"(old_value)
++                       : "memory");
++  return prev;
++}
++
++inline Atomic64 NoBarrier_AtomicExchange(volatile Atomic64* ptr,
++                                         Atomic64 new_value) {
++  __asm__ __volatile__("xchgq %1,%0"  // The lock prefix is implicit for xchg.
++                       : "=r"(new_value)
++                       : "m"(*ptr), "0"(new_value)
++                       : "memory");
++  return new_value;  // Now it's the previous value.
++}
++
++inline Atomic64 NoBarrier_AtomicIncrement(volatile Atomic64* ptr,
++                                          Atomic64 increment) {
++  Atomic64 temp = increment;
++  __asm__ __volatile__("lock; xaddq %0,%1"
++                       : "+r"(temp), "+m"(*ptr)
++                       :
++                       : "memory");
++  // temp now contains the previous value of *ptr
++  return temp + increment;
++}
++
++inline Atomic64 Barrier_AtomicIncrement(volatile Atomic64* ptr,
++                                        Atomic64 increment) {
++  Atomic64 temp = increment;
++  __asm__ __volatile__("lock; xaddq %0,%1"
++                       : "+r"(temp), "+m"(*ptr)
++                       :
++                       : "memory");
++  // temp now contains the previous value of *ptr
++  if (AtomicOps_Internalx86CPUFeatures.has_amd_lock_mb_bug) {
++    __asm__ __volatile__("lfence" : : : "memory");
++  }
++  return temp + increment;
++}
++
++inline void NoBarrier_Store(volatile Atomic64* ptr, Atomic64 value) {
++  *ptr = value;
++}
++
++inline void Acquire_Store(volatile Atomic64* ptr, Atomic64 value) {
++  *ptr = value;
++  MemoryBarrier();
++}
++
++inline void Release_Store(volatile Atomic64* ptr, Atomic64 value) {
++  ATOMICOPS_COMPILER_BARRIER();
++
++  *ptr = value;  // An x86 store acts as a release barrier
++                 // for current AMD/Intel chips as of Jan 2008.
++                 // See also Acquire_Load(), below.
++
++  // When new chips come out, check:
++  //  IA-32 Intel Architecture Software Developer's Manual, Volume 3:
++  //  System Programming Guide, Chatper 7: Multiple-processor management,
++  //  Section 7.2, Memory Ordering.
++  // Last seen at:
++  //   http://developer.intel.com/design/pentium4/manuals/index_new.htm
++  //
++  // x86 stores/loads fail to act as barriers for a few instructions (clflush
++  // maskmovdqu maskmovq movntdq movnti movntpd movntps movntq) but these are
++  // not generated by the compiler, and are rare.  Users of these instructions
++  // need to know about cache behaviour in any case since all of these involve
++  // either flushing cache lines or non-temporal cache hints.
++}
++
++inline Atomic64 NoBarrier_Load(volatile const Atomic64* ptr) {
++  return *ptr;
++}
++
++inline Atomic64 Acquire_Load(volatile const Atomic64* ptr) {
++  Atomic64 value = *ptr;  // An x86 load acts as a acquire barrier,
++                          // for current AMD/Intel chips as of Jan 2008.
++                          // See also Release_Store(), above.
++  ATOMICOPS_COMPILER_BARRIER();
++  return value;
++}
++
++inline Atomic64 Release_Load(volatile const Atomic64* ptr) {
++  MemoryBarrier();
++  return *ptr;
++}
++
++inline Atomic64 Acquire_CompareAndSwap(volatile Atomic64* ptr,
++                                       Atomic64 old_value,
++                                       Atomic64 new_value) {
++  Atomic64 x = NoBarrier_CompareAndSwap(ptr, old_value, new_value);
++  if (AtomicOps_Internalx86CPUFeatures.has_amd_lock_mb_bug) {
++    __asm__ __volatile__("lfence" : : : "memory");
++  }
++  return x;
++}
++
++inline Atomic64 Release_CompareAndSwap(volatile Atomic64* ptr,
++                                       Atomic64 old_value,
++                                       Atomic64 new_value) {
++  return NoBarrier_CompareAndSwap(ptr, old_value, new_value);
++}
++
++#endif  // defined(__x86_64__)
++
++}  // namespace base::subtle
++}  // namespace base
++
++#undef ATOMICOPS_COMPILER_BARRIER
++
++#endif  // CEF_INCLUDE_BASE_INTERNAL_CEF_ATOMICOPS_X86_GCC_H_
+--- cef_binary_3.3359.1774.gd49d25f_windows32/cmake/cef_variables.cmake.orig	2019-04-02 19:37:47.332457010 +0200
++++ cef_binary_3.3359.1774.gd49d25f_windows32/cmake/cef_variables.cmake	2019-03-09 14:17:10.333854000 +0100
+@@ -70,6 +70,8 @@
+ # Linux configuration.
+ #
+ 
++set(OS_LINUX true)
++set(OS_WINDOWS false)
+ if(OS_LINUX)
+   # Platform-specific compiler/linker flags.
+   set(CEF_LIBTYPE SHARED)
+@@ -185,21 +187,24 @@
+     )
+ 
+   # CEF directory paths.
++  # CEF directory paths.
+   set(CEF_RESOURCE_DIR        "${_CEF_ROOT}/Resources")
+-  set(CEF_BINARY_DIR          "${_CEF_ROOT}/${CMAKE_BUILD_TYPE}")
++  set(CEF_BINARY_DIR          "${_CEF_ROOT}/$<CONFIGURATION>")
+   set(CEF_BINARY_DIR_DEBUG    "${_CEF_ROOT}/Debug")
+   set(CEF_BINARY_DIR_RELEASE  "${_CEF_ROOT}/Release")
+ 
+   # CEF library paths.
+-  set(CEF_LIB_DEBUG   "${CEF_BINARY_DIR_DEBUG}/libcef.so")
+-  set(CEF_LIB_RELEASE "${CEF_BINARY_DIR_RELEASE}/libcef.so")
++  set(CEF_LIB_DEBUG   "${CEF_BINARY_DIR_DEBUG}/libcef.lib")
++  set(CEF_LIB_RELEASE "${CEF_BINARY_DIR_RELEASE}/libcef.lib")
+ 
+   # List of CEF binary files.
+   set(CEF_BINARY_FILES
+-    chrome-sandbox
+-    libcef.so
+-    libEGL.so
+-    libGLESv2.so
++    chrome_elf.dll
++    d3dcompiler_43.dll
++    d3dcompiler_47.dll
++    libcef.dll
++    libEGL.dll
++    libGLESv2.dll
+     natives_blob.bin
+     snapshot_blob.bin
+     v8_context_snapshot.bin
+@@ -216,6 +221,25 @@
+     icudtl.dat
+     locales
+     )
++
++  if(USE_SANDBOX)
++    list(APPEND CEF_COMPILER_DEFINES
++      PSAPI_VERSION=1   # Required by cef_sandbox.lib
++      CEF_USE_SANDBOX   # Used by apps to test if the sandbox is enabled
++      )
++
++    # Libraries required by cef_sandbox.lib.
++    set(CEF_SANDBOX_STANDARD_LIBS
++      dbghelp.lib
++      psapi.lib
++      version.lib
++      winmm.lib
++      )
++
++    # CEF sandbox library paths.
++    set(CEF_SANDBOX_LIB_DEBUG "${CEF_BINARY_DIR_DEBUG}/cef_sandbox.lib")
++    set(CEF_SANDBOX_LIB_RELEASE "${CEF_BINARY_DIR_RELEASE}/cef_sandbox.lib")
++  endif()
+ endif()
+ 
+ 
Index: docker/msys/cef_binary_3.3359.1774.gd49d25f_windows32.patch
===================================================================
--- docker/msys/cef_binary_3.3359.1774.gd49d25f_windows32.patch	(revision 920)
+++ 	(revision )
@@ -1,367 +1,0 @@
---- cef_binary_3.3359.1774.gd49d25f_windows32/include/internal/cef_string_wrappers.h.orig	2019-03-09 15:59:59.571378000 +0100
-+++ cef_binary_3.3359.1774.gd49d25f_windows32/include/internal/cef_string_wrappers.h	2019-03-09 16:00:08.284090000 +0100
-@@ -33,6 +33,7 @@
- 
- #include <memory.h>
- #include <string>
-+#include <cstring>
- 
- #include "include/base/cef_string16.h"
- #include "include/internal/cef_string_types.h"
---- cef_binary_3.3359.1774.gd49d25f_windows32/include/base/cef_bind_helpers.h.orig	2018-05-17 11:46:05.000000000 +0200
-+++ cef_binary_3.3359.1774.gd49d25f_windows32/include/base/cef_bind_helpers.h	2019-03-09 16:03:17.830725000 +0100
-@@ -272,12 +272,12 @@
- // MSVC warns when you try to use Base if T has a private destructor, the
- // common pattern for refcounted types. It does this even though no attempt to
- // instantiate Base is made.  We disable the warning for this definition.
--#if defined(OS_WIN)
-+#if defined(OS_WIN) && defined(COMPILER_MSVC)
- #pragma warning(push)
- #pragma warning(disable : 4624)
- #endif
-   struct Base : public T, public BaseMixin {};
--#if defined(OS_WIN)
-+#if defined(OS_WIN) && defined(COMPILER_MSVC)
- #pragma warning(pop)
- #endif
- 
---- cef_binary_3.3359.1774.gd49d25f_windows32/include/base/internal/cef_atomicops_x86_gcc.h.orig	2019-04-02 20:09:10.287478919 +0200
-+++ cef_binary_3.3359.1774.gd49d25f_windows32/include/base/internal/cef_atomicops_x86_gcc.h	2019-04-02 20:09:10.287478919 +0200
-@@ -0,0 +1,268 @@
-+// Copyright (c) 2011 Google Inc. All rights reserved.
-+//
-+// Redistribution and use in source and binary forms, with or without
-+// modification, are permitted provided that the following conditions are
-+// met:
-+//
-+//    * Redistributions of source code must retain the above copyright
-+// notice, this list of conditions and the following disclaimer.
-+//    * Redistributions in binary form must reproduce the above
-+// copyright notice, this list of conditions and the following disclaimer
-+// in the documentation and/or other materials provided with the
-+// distribution.
-+//    * Neither the name of Google Inc. nor the name Chromium Embedded
-+// Framework nor the names of its contributors may be used to endorse
-+// or promote products derived from this software without specific prior
-+// written permission.
-+//
-+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-+
-+// Do not include this header file directly. Use base/cef_atomicops.h
-+// instead.
-+
-+#ifndef CEF_INCLUDE_BASE_INTERNAL_CEF_ATOMICOPS_X86_GCC_H_
-+#define CEF_INCLUDE_BASE_INTERNAL_CEF_ATOMICOPS_X86_GCC_H_
-+
-+// This struct is not part of the public API of this module; clients may not
-+// use it.
-+// Features of this x86.  Values may not be correct before main() is run,
-+// but are set conservatively.
-+struct AtomicOps_x86CPUFeatureStruct {
-+  bool has_amd_lock_mb_bug;  // Processor has AMD memory-barrier bug; do lfence
-+                             // after acquire compare-and-swap.
-+};
-+extern struct AtomicOps_x86CPUFeatureStruct AtomicOps_Internalx86CPUFeatures;
-+
-+#define ATOMICOPS_COMPILER_BARRIER() __asm__ __volatile__("" : : : "memory")
-+
-+namespace base {
-+namespace subtle {
-+
-+// 32-bit low-level operations on any platform.
-+
-+inline Atomic32 NoBarrier_CompareAndSwap(volatile Atomic32* ptr,
-+                                         Atomic32 old_value,
-+                                         Atomic32 new_value) {
-+  Atomic32 prev;
-+  __asm__ __volatile__("lock; cmpxchgl %1,%2"
-+                       : "=a"(prev)
-+                       : "q"(new_value), "m"(*ptr), "0"(old_value)
-+                       : "memory");
-+  return prev;
-+}
-+
-+inline Atomic32 NoBarrier_AtomicExchange(volatile Atomic32* ptr,
-+                                         Atomic32 new_value) {
-+  __asm__ __volatile__("xchgl %1,%0"  // The lock prefix is implicit for xchg.
-+                       : "=r"(new_value)
-+                       : "m"(*ptr), "0"(new_value)
-+                       : "memory");
-+  return new_value;  // Now it's the previous value.
-+}
-+
-+inline Atomic32 NoBarrier_AtomicIncrement(volatile Atomic32* ptr,
-+                                          Atomic32 increment) {
-+  Atomic32 temp = increment;
-+  __asm__ __volatile__("lock; xaddl %0,%1"
-+                       : "+r"(temp), "+m"(*ptr)
-+                       :
-+                       : "memory");
-+  // temp now holds the old value of *ptr
-+  return temp + increment;
-+}
-+
-+inline Atomic32 Barrier_AtomicIncrement(volatile Atomic32* ptr,
-+                                        Atomic32 increment) {
-+  Atomic32 temp = increment;
-+  __asm__ __volatile__("lock; xaddl %0,%1"
-+                       : "+r"(temp), "+m"(*ptr)
-+                       :
-+                       : "memory");
-+  // temp now holds the old value of *ptr
-+  if (AtomicOps_Internalx86CPUFeatures.has_amd_lock_mb_bug) {
-+    __asm__ __volatile__("lfence" : : : "memory");
-+  }
-+  return temp + increment;
-+}
-+
-+inline Atomic32 Acquire_CompareAndSwap(volatile Atomic32* ptr,
-+                                       Atomic32 old_value,
-+                                       Atomic32 new_value) {
-+  Atomic32 x = NoBarrier_CompareAndSwap(ptr, old_value, new_value);
-+  if (AtomicOps_Internalx86CPUFeatures.has_amd_lock_mb_bug) {
-+    __asm__ __volatile__("lfence" : : : "memory");
-+  }
-+  return x;
-+}
-+
-+inline Atomic32 Release_CompareAndSwap(volatile Atomic32* ptr,
-+                                       Atomic32 old_value,
-+                                       Atomic32 new_value) {
-+  return NoBarrier_CompareAndSwap(ptr, old_value, new_value);
-+}
-+
-+inline void NoBarrier_Store(volatile Atomic32* ptr, Atomic32 value) {
-+  *ptr = value;
-+}
-+
-+inline void MemoryBarrier() {
-+  __asm__ __volatile__("mfence" : : : "memory");
-+}
-+
-+inline void Acquire_Store(volatile Atomic32* ptr, Atomic32 value) {
-+  *ptr = value;
-+  MemoryBarrier();
-+}
-+
-+inline void Release_Store(volatile Atomic32* ptr, Atomic32 value) {
-+  ATOMICOPS_COMPILER_BARRIER();
-+  *ptr = value;  // An x86 store acts as a release barrier.
-+  // See comments in Atomic64 version of Release_Store(), below.
-+}
-+
-+inline Atomic32 NoBarrier_Load(volatile const Atomic32* ptr) {
-+  return *ptr;
-+}
-+
-+inline Atomic32 Acquire_Load(volatile const Atomic32* ptr) {
-+  Atomic32 value = *ptr;  // An x86 load acts as a acquire barrier.
-+  // See comments in Atomic64 version of Release_Store(), below.
-+  ATOMICOPS_COMPILER_BARRIER();
-+  return value;
-+}
-+
-+inline Atomic32 Release_Load(volatile const Atomic32* ptr) {
-+  MemoryBarrier();
-+  return *ptr;
-+}
-+
-+#if defined(__x86_64__)
-+
-+// 64-bit low-level operations on 64-bit platform.
-+
-+inline Atomic64 NoBarrier_CompareAndSwap(volatile Atomic64* ptr,
-+                                         Atomic64 old_value,
-+                                         Atomic64 new_value) {
-+  Atomic64 prev;
-+  __asm__ __volatile__("lock; cmpxchgq %1,%2"
-+                       : "=a"(prev)
-+                       : "q"(new_value), "m"(*ptr), "0"(old_value)
-+                       : "memory");
-+  return prev;
-+}
-+
-+inline Atomic64 NoBarrier_AtomicExchange(volatile Atomic64* ptr,
-+                                         Atomic64 new_value) {
-+  __asm__ __volatile__("xchgq %1,%0"  // The lock prefix is implicit for xchg.
-+                       : "=r"(new_value)
-+                       : "m"(*ptr), "0"(new_value)
-+                       : "memory");
-+  return new_value;  // Now it's the previous value.
-+}
-+
-+inline Atomic64 NoBarrier_AtomicIncrement(volatile Atomic64* ptr,
-+                                          Atomic64 increment) {
-+  Atomic64 temp = increment;
-+  __asm__ __volatile__("lock; xaddq %0,%1"
-+                       : "+r"(temp), "+m"(*ptr)
-+                       :
-+                       : "memory");
-+  // temp now contains the previous value of *ptr
-+  return temp + increment;
-+}
-+
-+inline Atomic64 Barrier_AtomicIncrement(volatile Atomic64* ptr,
-+                                        Atomic64 increment) {
-+  Atomic64 temp = increment;
-+  __asm__ __volatile__("lock; xaddq %0,%1"
-+                       : "+r"(temp), "+m"(*ptr)
-+                       :
-+                       : "memory");
-+  // temp now contains the previous value of *ptr
-+  if (AtomicOps_Internalx86CPUFeatures.has_amd_lock_mb_bug) {
-+    __asm__ __volatile__("lfence" : : : "memory");
-+  }
-+  return temp + increment;
-+}
-+
-+inline void NoBarrier_Store(volatile Atomic64* ptr, Atomic64 value) {
-+  *ptr = value;
-+}
-+
-+inline void Acquire_Store(volatile Atomic64* ptr, Atomic64 value) {
-+  *ptr = value;
-+  MemoryBarrier();
-+}
-+
-+inline void Release_Store(volatile Atomic64* ptr, Atomic64 value) {
-+  ATOMICOPS_COMPILER_BARRIER();
-+
-+  *ptr = value;  // An x86 store acts as a release barrier
-+                 // for current AMD/Intel chips as of Jan 2008.
-+                 // See also Acquire_Load(), below.
-+
-+  // When new chips come out, check:
-+  //  IA-32 Intel Architecture Software Developer's Manual, Volume 3:
-+  //  System Programming Guide, Chatper 7: Multiple-processor management,
-+  //  Section 7.2, Memory Ordering.
-+  // Last seen at:
-+  //   http://developer.intel.com/design/pentium4/manuals/index_new.htm
-+  //
-+  // x86 stores/loads fail to act as barriers for a few instructions (clflush
-+  // maskmovdqu maskmovq movntdq movnti movntpd movntps movntq) but these are
-+  // not generated by the compiler, and are rare.  Users of these instructions
-+  // need to know about cache behaviour in any case since all of these involve
-+  // either flushing cache lines or non-temporal cache hints.
-+}
-+
-+inline Atomic64 NoBarrier_Load(volatile const Atomic64* ptr) {
-+  return *ptr;
-+}
-+
-+inline Atomic64 Acquire_Load(volatile const Atomic64* ptr) {
-+  Atomic64 value = *ptr;  // An x86 load acts as a acquire barrier,
-+                          // for current AMD/Intel chips as of Jan 2008.
-+                          // See also Release_Store(), above.
-+  ATOMICOPS_COMPILER_BARRIER();
-+  return value;
-+}
-+
-+inline Atomic64 Release_Load(volatile const Atomic64* ptr) {
-+  MemoryBarrier();
-+  return *ptr;
-+}
-+
-+inline Atomic64 Acquire_CompareAndSwap(volatile Atomic64* ptr,
-+                                       Atomic64 old_value,
-+                                       Atomic64 new_value) {
-+  Atomic64 x = NoBarrier_CompareAndSwap(ptr, old_value, new_value);
-+  if (AtomicOps_Internalx86CPUFeatures.has_amd_lock_mb_bug) {
-+    __asm__ __volatile__("lfence" : : : "memory");
-+  }
-+  return x;
-+}
-+
-+inline Atomic64 Release_CompareAndSwap(volatile Atomic64* ptr,
-+                                       Atomic64 old_value,
-+                                       Atomic64 new_value) {
-+  return NoBarrier_CompareAndSwap(ptr, old_value, new_value);
-+}
-+
-+#endif  // defined(__x86_64__)
-+
-+}  // namespace base::subtle
-+}  // namespace base
-+
-+#undef ATOMICOPS_COMPILER_BARRIER
-+
-+#endif  // CEF_INCLUDE_BASE_INTERNAL_CEF_ATOMICOPS_X86_GCC_H_
---- cef_binary_3.3359.1774.gd49d25f_windows32/cmake/cef_variables.cmake.orig	2019-04-02 19:37:47.332457010 +0200
-+++ cef_binary_3.3359.1774.gd49d25f_windows32/cmake/cef_variables.cmake	2019-03-09 14:17:10.333854000 +0100
-@@ -70,6 +70,8 @@
- # Linux configuration.
- #
- 
-+set(OS_LINUX true)
-+set(OS_WINDOWS false)
- if(OS_LINUX)
-   # Platform-specific compiler/linker flags.
-   set(CEF_LIBTYPE SHARED)
-@@ -185,21 +187,24 @@
-     )
- 
-   # CEF directory paths.
-+  # CEF directory paths.
-   set(CEF_RESOURCE_DIR        "${_CEF_ROOT}/Resources")
--  set(CEF_BINARY_DIR          "${_CEF_ROOT}/${CMAKE_BUILD_TYPE}")
-+  set(CEF_BINARY_DIR          "${_CEF_ROOT}/$<CONFIGURATION>")
-   set(CEF_BINARY_DIR_DEBUG    "${_CEF_ROOT}/Debug")
-   set(CEF_BINARY_DIR_RELEASE  "${_CEF_ROOT}/Release")
- 
-   # CEF library paths.
--  set(CEF_LIB_DEBUG   "${CEF_BINARY_DIR_DEBUG}/libcef.so")
--  set(CEF_LIB_RELEASE "${CEF_BINARY_DIR_RELEASE}/libcef.so")
-+  set(CEF_LIB_DEBUG   "${CEF_BINARY_DIR_DEBUG}/libcef.lib")
-+  set(CEF_LIB_RELEASE "${CEF_BINARY_DIR_RELEASE}/libcef.lib")
- 
-   # List of CEF binary files.
-   set(CEF_BINARY_FILES
--    chrome-sandbox
--    libcef.so
--    libEGL.so
--    libGLESv2.so
-+    chrome_elf.dll
-+    d3dcompiler_43.dll
-+    d3dcompiler_47.dll
-+    libcef.dll
-+    libEGL.dll
-+    libGLESv2.dll
-     natives_blob.bin
-     snapshot_blob.bin
-     v8_context_snapshot.bin
-@@ -216,6 +221,25 @@
-     icudtl.dat
-     locales
-     )
-+
-+  if(USE_SANDBOX)
-+    list(APPEND CEF_COMPILER_DEFINES
-+      PSAPI_VERSION=1   # Required by cef_sandbox.lib
-+      CEF_USE_SANDBOX   # Used by apps to test if the sandbox is enabled
-+      )
-+
-+    # Libraries required by cef_sandbox.lib.
-+    set(CEF_SANDBOX_STANDARD_LIBS
-+      dbghelp.lib
-+      psapi.lib
-+      version.lib
-+      winmm.lib
-+      )
-+
-+    # CEF sandbox library paths.
-+    set(CEF_SANDBOX_LIB_DEBUG "${CEF_BINARY_DIR_DEBUG}/cef_sandbox.lib")
-+    set(CEF_SANDBOX_LIB_RELEASE "${CEF_BINARY_DIR_RELEASE}/cef_sandbox.lib")
-+  endif()
- endif()
- 
- 
Index: docker/msys/cefpython-66.0.patch
===================================================================
--- docker/msys/cefpython-66.0.patch	(revision 936)
+++ docker/msys/cefpython-66.0.patch	(revision 936)
@@ -0,0 +1,224 @@
+--- cefpython-66.0/tools/build_cpp_projects.py.orig	2019-04-02 16:58:20.961263518 +0200
++++ cefpython-66.0/tools/build_cpp_projects.py	2019-03-09 16:32:28.031876000 +0100
+@@ -1,4 +1,4 @@
+-# Copyright (c) 2017 CEF Python, see the Authors file.
++# Copyright (c) 2017 CEF Python, see the Authors file
+ # All rights reserved. Licensed under BSD 3-clause license.
+ # Project website: https://github.com/cztomczak/cefpython
+ 
+@@ -46,16 +46,19 @@
+ 
+ # Compiler args
+ COMPILER_ARGS = [
+-    "/EHsc",
++    #"/EHsc",
+ ]
+ subprocess_COMPILER_ARGS = [
+-    "/MT",
++    #"/MT",
++    "-pthread",
+ ]
+ 
+ # Linker args
+ subprocess_LINKER_ARGS = [
+-    "/MANIFEST:NO",
+-    "/LARGEADDRESSAWARE",
++    #"/MANIFEST:NO",
++    #"/LARGEADDRESSAWARE",
++    "-fstack-protector-all",
++    "-Wl,--subsystem,windows"
+ ]
+ 
+ # Command line args
+@@ -110,11 +112,11 @@
+ def get_compiler(static=False):
+     # NOTES:
+     # - VS2008 and VS2010 are both using distutils/msvc9compiler.py
+-    compiler = new_compiler()
++    compiler = new_compiler(verbose = True)
+     # Must initialize so that "compile_options" and others are available
+-    compiler.initialize()
++    #compiler.initialize()
+     if static:
+-        compiler.compile_options.remove("/MD")
++        #compiler.compile_options.remove("/MD")
+         # Overwrite function that adds /MANIFESTFILE, as for subprocess
+         # manifest is disabled. Otherwise warning LNK4075 is generated.
+         if hasattr(compiler, "manifest_setup_ldargs"):
+@@ -179,11 +181,13 @@
+                                  output_progname="subprocess",
+                                  output_dir=BUILD_SUBPROCESS,
+                                  libraries=["libcef",
+-                                            "libcef_dll_wrapper_MT"],
++                                            "cef_dll_wrapper",
++                                            "libcef"],
+                                  library_dirs=[lib_dir, lib_dir_vs],
+                                  # TODO linker flags for Linux/Mac
+                                  extra_preargs=None,
+-                                 extra_postargs=subprocess_LINKER_ARGS)
++                                 extra_postargs=subprocess_LINKER_ARGS,
++                                 target_lang="c++")
+     else:
+         print("[build_cpp_projects.py] Executable is up-to-date: subprocess")
+ 
+--- cefpython-66.0/tools/cython_setup.py.orig	2019-04-02 16:58:31.753618071 +0200
++++ cefpython-66.0/tools/cython_setup.py	2019-03-09 16:53:19.516724000 +0100
+@@ -129,6 +129,7 @@
+                 r"C:\\Program Files\\Microsoft SDKs\\Windows\\v7.0\\Lib",
+                 # Visual Studio 2008 installation
+                 r"C:\\Program Files\\Microsoft SDKs\\Windows\\v6.0A\\Lib",
++                r"C:\\msys64\\mingw32\\lib"
+             ]
+         elif ARCH64:
+             winsdk_libs = [
+@@ -180,8 +181,37 @@
+         #
+         # The above warning LNK4217 is caused by the warning below which occurs
+         # when building the client_handler.lib static library:
+-        extra_compile_args.extend(["/EHsc", "/wd4305"])
+-        extra_link_args.extend(["/ignore:4217"])
++        #extra_compile_args.extend(["/EHsc", "/wd4305"])
++        #extra_link_args.extend(["/ignore:4217"])
++        if FAST_FLAG:
++            extra_compile_args.append("-O0")
++        else:
++            extra_compile_args.append("-O3")
++
++        extra_compile_args.extend([
++                "-DNDEBUG",
++                "-std=gnu++11",
++        ])
++        os.environ["CC"] = "g++"
++        os.environ["CXX"] = "g++"
++        extra_compile_args.extend(["-std=gnu++11"])
++
++        # Fix "ImportError ... undefined symbol ..." caused by CEF's
++        # include/base/ headers by adding the -flto flag (Issue #230).
++        # Unfortunately -flto prolongs compilation time significantly.
++        # More on the other flags: https://stackoverflow.com/questions/
++        # 6687630/ .
++
++        if FAST_FLAG:
++            extra_compile_args.extend(["-flto"])
++            extra_link_args.extend(["-flto"])
++        else:
++            extra_compile_args.extend(["-flto",
++                                       "-fdata-sections",
++                                       "-ffunction-sections"])
++            extra_link_args.extend(["-flto",
++                                    "-Wl,--gc-sections"])
++        extra_link_args.extend(["-fstack-protector-all"])
+ 
+     if LINUX or MAC:
+         # Compiler flags
+@@ -365,12 +395,13 @@
+     libraries = list()
+     if WINDOWS:
+         libraries.extend([
++            "cef_dll_wrapper",
+             "libcef",
+-            "libcef_dll_wrapper_MD",
+             "User32",
+             "cefpython_app",
+             "cpp_utils",
+             "client_handler",
++            "gdi32"
+         ])
+     elif MAC:
+         libraries.extend([
+--- cefpython-66.0/src/subprocess/main.cpp.orig	2019-04-02 20:36:34.016395754 +0200
++++ cefpython-66.0/src/subprocess/main.cpp	2019-04-02 20:39:33.491183098 +0200
+@@ -7,10 +7,10 @@
+ #if defined(OS_WIN)
+ 
+ #include <windows.h>
+-int APIENTRY wWinMain(HINSTANCE hInstance,
+-                      HINSTANCE hPrevInstance,
+-                      LPTSTR    lpCmdLine,
+-                      int       nCmdShow)
++int APIENTRY WinMain(HINSTANCE hInstance,
++                     HINSTANCE hPrevInstance,
++                     LPSTR     lpCmdLine,
++                     int       nCmdShow)
+ {
+ 	UNREFERENCED_PARAMETER(hPrevInstance);
+ 	UNREFERENCED_PARAMETER(lpCmdLine);
+--- cefpython-66.0/tools/make_installer.py.orig	2018-08-20 19:51:17.000000000 +0200
++++ cefpython-66.0/tools/make_installer.py	2019-04-02 20:59:22.372933492 +0200
+@@ -102,7 +102,7 @@
+     create_empty_log_file(os.path.join(PKG_DIR, "debug.log"))
+     create_empty_log_file(os.path.join(PKG_DIR, "examples/debug.log"))
+ 
+-    copy_cpp_extension_dependencies_issue359(PKG_DIR)
++    #copy_cpp_extension_dependencies_issue359(PKG_DIR)
+ 
+     print("[make_installer.py] Done. Installer package created: {setup_dir}"
+           .format(setup_dir=SETUP_DIR))
+--- cefpython-66.0/tools/build.py.orig	2019-04-02 16:58:17.137138263 +0200
++++ cefpython-66.0/tools/build.py	2019-04-12 21:32:28.414197037 +0200
+@@ -79,6 +79,7 @@
+ # Command line args variables
+ SYS_ARGV_ORIGINAL = None
+ VERSION = ""
++NO_RUN_TESTS = False
+ NO_RUN_EXAMPLES = False
+ DEBUG_FLAG = False
+ FAST_FLAG = False
+@@ -125,7 +126,7 @@
+ 
+ def command_line_args():
+     global DEBUG_FLAG, FAST_FLAG, CLEAN_FLAG, KIVY_FLAG, HELLO_WORLD_FLAG, \
+-           REBUILD_CPP, VERSION, NO_RUN_EXAMPLES
++           REBUILD_CPP, VERSION, NO_RUN_TESTS, NO_RUN_EXAMPLES
+ 
+     VERSION = get_version_from_command_line_args(__file__)
+     # Other scripts called by this script expect that version number
+@@ -140,6 +141,11 @@
+     global SYS_ARGV_ORIGINAL
+     SYS_ARGV_ORIGINAL = copy.copy(sys.argv)
+ 
++    if "--no-run-tests" in sys.argv:
++        NO_RUN_TESTS = True
++        print("[build.py] Running tests disabled (--no-run-tests)")
++        sys.argv.remove("--no-run-tests")
++
+     if "--no-run-examples" in sys.argv:
+         NO_RUN_EXAMPLES = True
+         print("[build.py] Running examples disabled (--no-run-examples)")
+@@ -820,8 +826,8 @@
+         sys.exit(1)
+ 
+     # Move the cefpython module
+-    module_pattern = MODULE_NAME_TEMPLATE.format(pyversion=PYVERSION+"*",
+-                                                 ext=MODULE_EXT)
++    module_pattern = "cefpython_py{pyversion}-cpython-{pyversion}m.dll".\
++                     format(pyversion=PYVERSION+"*", ext=MODULE_EXT)
+     module_pattern = "./build/lib*/" + module_pattern
+     move_file_by_pattern(module_pattern, os.path.join(CEFPYTHON_BINARY,
+                                                       MODULE_NAME))
+@@ -902,15 +908,16 @@
+     delete_directory_reliably(setup_installer_dir)
+ 
+     # Run unittests
+-    print("[build.py] Run unittests")
+-    test_runner = os.path.join(UNITTESTS_DIR, "_test_runner.py")
+-    command = ("\"{python}\" {test_runner}"
+-               .format(python=sys.executable,
+-                       test_runner=test_runner))
+-    ret = os.system(command)
+-    if ret != 0:
+-        print("[build.py] ERROR while running unit tests")
+-        sys.exit(1)
++    if not NO_RUN_TESTS:
++        print("[build.py] Run unittests")
++        test_runner = os.path.join(UNITTESTS_DIR, "_test_runner.py")
++        command = ("\"{python}\" {test_runner}"
++                   .format(python=sys.executable,
++                           test_runner=test_runner))
++        ret = os.system(command)
++        if ret != 0:
++            print("[build.py] ERROR while running unit tests")
++            sys.exit(1)
+ 
+     # Run examples
+     if not NO_RUN_EXAMPLES:
Index: docker/msys/cefpython-66.0.patch
===================================================================
--- docker/msys/cefpython-66.0.patch	(revision 936)
+++ 	(revision )
@@ -1,224 +1,0 @@
---- cefpython-66.0/tools/build_cpp_projects.py.orig	2019-04-02 16:58:20.961263518 +0200
-+++ cefpython-66.0/tools/build_cpp_projects.py	2019-03-09 16:32:28.031876000 +0100
-@@ -1,4 +1,4 @@
--# Copyright (c) 2017 CEF Python, see the Authors file.
-+# Copyright (c) 2017 CEF Python, see the Authors file
- # All rights reserved. Licensed under BSD 3-clause license.
- # Project website: https://github.com/cztomczak/cefpython
- 
-@@ -46,16 +46,19 @@
- 
- # Compiler args
- COMPILER_ARGS = [
--    "/EHsc",
-+    #"/EHsc",
- ]
- subprocess_COMPILER_ARGS = [
--    "/MT",
-+    #"/MT",
-+    "-pthread",
- ]
- 
- # Linker args
- subprocess_LINKER_ARGS = [
--    "/MANIFEST:NO",
--    "/LARGEADDRESSAWARE",
-+    #"/MANIFEST:NO",
-+    #"/LARGEADDRESSAWARE",
-+    "-fstack-protector-all",
-+    "-Wl,--subsystem,windows"
- ]
- 
- # Command line args
-@@ -110,11 +112,11 @@
- def get_compiler(static=False):
-     # NOTES:
-     # - VS2008 and VS2010 are both using distutils/msvc9compiler.py
--    compiler = new_compiler()
-+    compiler = new_compiler(verbose = True)
-     # Must initialize so that "compile_options" and others are available
--    compiler.initialize()
-+    #compiler.initialize()
-     if static:
--        compiler.compile_options.remove("/MD")
-+        #compiler.compile_options.remove("/MD")
-         # Overwrite function that adds /MANIFESTFILE, as for subprocess
-         # manifest is disabled. Otherwise warning LNK4075 is generated.
-         if hasattr(compiler, "manifest_setup_ldargs"):
-@@ -179,11 +181,13 @@
-                                  output_progname="subprocess",
-                                  output_dir=BUILD_SUBPROCESS,
-                                  libraries=["libcef",
--                                            "libcef_dll_wrapper_MT"],
-+                                            "cef_dll_wrapper",
-+                                            "libcef"],
-                                  library_dirs=[lib_dir, lib_dir_vs],
-                                  # TODO linker flags for Linux/Mac
-                                  extra_preargs=None,
--                                 extra_postargs=subprocess_LINKER_ARGS)
-+                                 extra_postargs=subprocess_LINKER_ARGS,
-+                                 target_lang="c++")
-     else:
-         print("[build_cpp_projects.py] Executable is up-to-date: subprocess")
- 
---- cefpython-66.0/tools/cython_setup.py.orig	2019-04-02 16:58:31.753618071 +0200
-+++ cefpython-66.0/tools/cython_setup.py	2019-03-09 16:53:19.516724000 +0100
-@@ -129,6 +129,7 @@
-                 r"C:\\Program Files\\Microsoft SDKs\\Windows\\v7.0\\Lib",
-                 # Visual Studio 2008 installation
-                 r"C:\\Program Files\\Microsoft SDKs\\Windows\\v6.0A\\Lib",
-+                r"C:\\msys64\\mingw32\\lib"
-             ]
-         elif ARCH64:
-             winsdk_libs = [
-@@ -180,8 +181,37 @@
-         #
-         # The above warning LNK4217 is caused by the warning below which occurs
-         # when building the client_handler.lib static library:
--        extra_compile_args.extend(["/EHsc", "/wd4305"])
--        extra_link_args.extend(["/ignore:4217"])
-+        #extra_compile_args.extend(["/EHsc", "/wd4305"])
-+        #extra_link_args.extend(["/ignore:4217"])
-+        if FAST_FLAG:
-+            extra_compile_args.append("-O0")
-+        else:
-+            extra_compile_args.append("-O3")
-+
-+        extra_compile_args.extend([
-+                "-DNDEBUG",
-+                "-std=gnu++11",
-+        ])
-+        os.environ["CC"] = "g++"
-+        os.environ["CXX"] = "g++"
-+        extra_compile_args.extend(["-std=gnu++11"])
-+
-+        # Fix "ImportError ... undefined symbol ..." caused by CEF's
-+        # include/base/ headers by adding the -flto flag (Issue #230).
-+        # Unfortunately -flto prolongs compilation time significantly.
-+        # More on the other flags: https://stackoverflow.com/questions/
-+        # 6687630/ .
-+
-+        if FAST_FLAG:
-+            extra_compile_args.extend(["-flto"])
-+            extra_link_args.extend(["-flto"])
-+        else:
-+            extra_compile_args.extend(["-flto",
-+                                       "-fdata-sections",
-+                                       "-ffunction-sections"])
-+            extra_link_args.extend(["-flto",
-+                                    "-Wl,--gc-sections"])
-+        extra_link_args.extend(["-fstack-protector-all"])
- 
-     if LINUX or MAC:
-         # Compiler flags
-@@ -365,12 +395,13 @@
-     libraries = list()
-     if WINDOWS:
-         libraries.extend([
-+            "cef_dll_wrapper",
-             "libcef",
--            "libcef_dll_wrapper_MD",
-             "User32",
-             "cefpython_app",
-             "cpp_utils",
-             "client_handler",
-+            "gdi32"
-         ])
-     elif MAC:
-         libraries.extend([
---- cefpython-66.0/src/subprocess/main.cpp.orig	2019-04-02 20:36:34.016395754 +0200
-+++ cefpython-66.0/src/subprocess/main.cpp	2019-04-02 20:39:33.491183098 +0200
-@@ -7,10 +7,10 @@
- #if defined(OS_WIN)
- 
- #include <windows.h>
--int APIENTRY wWinMain(HINSTANCE hInstance,
--                      HINSTANCE hPrevInstance,
--                      LPTSTR    lpCmdLine,
--                      int       nCmdShow)
-+int APIENTRY WinMain(HINSTANCE hInstance,
-+                     HINSTANCE hPrevInstance,
-+                     LPSTR     lpCmdLine,
-+                     int       nCmdShow)
- {
- 	UNREFERENCED_PARAMETER(hPrevInstance);
- 	UNREFERENCED_PARAMETER(lpCmdLine);
---- cefpython-66.0/tools/make_installer.py.orig	2018-08-20 19:51:17.000000000 +0200
-+++ cefpython-66.0/tools/make_installer.py	2019-04-02 20:59:22.372933492 +0200
-@@ -102,7 +102,7 @@
-     create_empty_log_file(os.path.join(PKG_DIR, "debug.log"))
-     create_empty_log_file(os.path.join(PKG_DIR, "examples/debug.log"))
- 
--    copy_cpp_extension_dependencies_issue359(PKG_DIR)
-+    #copy_cpp_extension_dependencies_issue359(PKG_DIR)
- 
-     print("[make_installer.py] Done. Installer package created: {setup_dir}"
-           .format(setup_dir=SETUP_DIR))
---- cefpython-66.0/tools/build.py.orig	2019-04-02 16:58:17.137138263 +0200
-+++ cefpython-66.0/tools/build.py	2019-04-12 21:32:28.414197037 +0200
-@@ -79,6 +79,7 @@
- # Command line args variables
- SYS_ARGV_ORIGINAL = None
- VERSION = ""
-+NO_RUN_TESTS = False
- NO_RUN_EXAMPLES = False
- DEBUG_FLAG = False
- FAST_FLAG = False
-@@ -125,7 +126,7 @@
- 
- def command_line_args():
-     global DEBUG_FLAG, FAST_FLAG, CLEAN_FLAG, KIVY_FLAG, HELLO_WORLD_FLAG, \
--           REBUILD_CPP, VERSION, NO_RUN_EXAMPLES
-+           REBUILD_CPP, VERSION, NO_RUN_TESTS, NO_RUN_EXAMPLES
- 
-     VERSION = get_version_from_command_line_args(__file__)
-     # Other scripts called by this script expect that version number
-@@ -140,6 +141,11 @@
-     global SYS_ARGV_ORIGINAL
-     SYS_ARGV_ORIGINAL = copy.copy(sys.argv)
- 
-+    if "--no-run-tests" in sys.argv:
-+        NO_RUN_TESTS = True
-+        print("[build.py] Running tests disabled (--no-run-tests)")
-+        sys.argv.remove("--no-run-tests")
-+
-     if "--no-run-examples" in sys.argv:
-         NO_RUN_EXAMPLES = True
-         print("[build.py] Running examples disabled (--no-run-examples)")
-@@ -820,8 +826,8 @@
-         sys.exit(1)
- 
-     # Move the cefpython module
--    module_pattern = MODULE_NAME_TEMPLATE.format(pyversion=PYVERSION+"*",
--                                                 ext=MODULE_EXT)
-+    module_pattern = "cefpython_py{pyversion}-cpython-{pyversion}m.dll".\
-+                     format(pyversion=PYVERSION+"*", ext=MODULE_EXT)
-     module_pattern = "./build/lib*/" + module_pattern
-     move_file_by_pattern(module_pattern, os.path.join(CEFPYTHON_BINARY,
-                                                       MODULE_NAME))
-@@ -902,15 +908,16 @@
-     delete_directory_reliably(setup_installer_dir)
- 
-     # Run unittests
--    print("[build.py] Run unittests")
--    test_runner = os.path.join(UNITTESTS_DIR, "_test_runner.py")
--    command = ("\"{python}\" {test_runner}"
--               .format(python=sys.executable,
--                       test_runner=test_runner))
--    ret = os.system(command)
--    if ret != 0:
--        print("[build.py] ERROR while running unit tests")
--        sys.exit(1)
-+    if not NO_RUN_TESTS:
-+        print("[build.py] Run unittests")
-+        test_runner = os.path.join(UNITTESTS_DIR, "_test_runner.py")
-+        command = ("\"{python}\" {test_runner}"
-+                   .format(python=sys.executable,
-+                           test_runner=test_runner))
-+        ret = os.system(command)
-+        if ret != 0:
-+            print("[build.py] ERROR while running unit tests")
-+            sys.exit(1)
- 
-     # Run examples
-     if not NO_RUN_EXAMPLES:
Index: docker/msys/py2exe.patch
===================================================================
--- docker/msys/py2exe.patch	(revision 936)
+++ docker/msys/py2exe.patch	(revision 936)
@@ -0,0 +1,736 @@
+diff --git a/py2exe/distutils_buildexe.py b/py2exe/distutils_buildexe.py
+index ae8aca3..d809641 100644
+--- a/py2exe/distutils_buildexe.py
++++ b/py2exe/distutils_buildexe.py
+@@ -154,6 +154,7 @@ class py2exe(Command):
+         self.ascii = 0
+         self.custom_boot_script = None
+         self.use_assembly = False
++        self.gi_namespaces = []
+ 
+     def finalize_options (self):
+         self.optimize = int(self.optimize)
+@@ -239,6 +240,7 @@ class py2exe(Command):
+                             excludes = self.excludes,
+                             ignores = self.ignores,
+                             packages = self.packages,
++                            gi_namespaces = self.gi_namespaces,
+                             dist_dist = self.dist_dir,
+                             dll_excludes = self.dll_excludes,
+                             typelibs = self.typelibs,
+diff --git a/py2exe/dllfinder.py b/py2exe/dllfinder.py
+index 4e5e76c..bb43f9e 100644
+--- a/py2exe/dllfinder.py
++++ b/py2exe/dllfinder.py
+@@ -68,7 +68,8 @@ class DllFinder:
+             if dll in self._loaded_dlls:
+                 continue
+             for dep_dll in self.bind_image(dll):
+-                if dep_dll in self._loaded_dlls:
++                bname = os.path.basename(dep_dll).lower()
++                if bname in self._loaded_dlls:
+                     continue
+                 dll_type = self.determine_dll_type(dep_dll)
+                 if dll_type is None:
+@@ -144,7 +145,8 @@ class DllFinder:
+         deps = self.bind_image(imagename)
+         if pydll in [d.lower() for d in deps]:
+             return "EXT"
+-        if fnm.startswith(windir + os.sep) or fnm.startswith(sysdir + os.sep):
++        if fnm.startswith(windir + os.sep) or fnm.startswith(sysdir + os.sep) or \
++           fnm.startswith(windir + '\\') or fnm.startswith(sysdir + '\\'):
+             return None
+         return "DLL"
+ 
+diff --git a/py2exe/gihelper.py b/py2exe/gihelper.py
+index e69de29..f597692 100644
+--- a/py2exe/gihelper.py
++++ b/py2exe/gihelper.py
+@@ -0,0 +1,58 @@
++
++import cffi
++
++class GIHelper(object):
++    _cdef="""
++        typedef char gchar;
++        typedef int gint;
++        typedef uint32_t guint32;
++        typedef guint32 GQuark;
++
++        typedef struct {
++          GQuark    domain;
++          gint      code;
++          gchar     *message;
++        } GError;
++
++        typedef struct _GITypelib GITypelib;
++        typedef struct _GIRepository         GIRepository;
++
++        typedef enum
++        {
++          G_IREPOSITORY_LOAD_FLAG_LAZY = 1
++        } GIRepositoryLoadFlags;
++
++        GIRepository *g_irepository_get_default   (void);
++
++        GITypelib *    g_irepository_require       (GIRepository *repository,
++                               const gchar  *namespace_,
++                               const gchar  *version,
++                               GIRepositoryLoadFlags flags,
++                               GError      **error);
++
++        const gchar * g_irepository_get_shared_library (GIRepository *repository,
++                                const gchar  *namespace_);
++        """
++
++    def __init__(self):
++        self._ffi = cffi.FFI()
++        self._ffi.cdef(self._cdef)
++
++        self._lib = self._ffi.dlopen("libgirepository-1.0-1.dll")
++
++        self._repo=self._lib.g_irepository_get_default()
++
++        self._error = self._ffi.new("GError**")
++
++    def getSharedLibraries(self, namespace, version):
++        typelib = self._lib.g_irepository_require(self._repo,
++                                        bytes(namespace, "utf-8"),
++                                        bytes(version, "utf-8"),
++                                        0, self._error)
++        if typelib == self._ffi.NULL:
++            return []
++        else:
++            return str(
++                self._ffi.string(
++                    self._lib.g_irepository_get_shared_library(
++                        self._repo, bytes(namespace, "utf-8"))), "utf-8").split(",")
+diff --git a/py2exe/mf3.py b/py2exe/mf3.py
+index f645740..ec1f261 100644
+--- a/py2exe/mf3.py
++++ b/py2exe/mf3.py
+@@ -5,6 +5,7 @@
+ 
+ # XXX XXX XXX Does not yet support PEP 452 namespace packages!
+ 
++from . import gihelper
+ from collections import defaultdict
+ import dis
+ import importlib
+@@ -21,6 +22,9 @@ LOAD_CONST = dis.opname.index('LOAD_CONST')
+ IMPORT_NAME = dis.opname.index('IMPORT_NAME')
+ STORE_NAME = dis.opname.index('STORE_NAME')
+ STORE_GLOBAL = dis.opname.index('STORE_GLOBAL')
++LOAD_NAME = dis.opname.index('LOAD_NAME')
++LOAD_METHOD = dis.opname.index('LOAD_METHOD')
++CALL_METHOD = dis.opname.index('CALL_METHOD')
+ STORE_OPS = [STORE_NAME, STORE_GLOBAL]
+ HAVE_ARGUMENT = dis.HAVE_ARGUMENT
+ 
+@@ -63,7 +67,7 @@ class ModuleFinder:
+         self._depgraph = defaultdict(set)
+         self._indent = ""
+         self._package_paths = defaultdict(list)
+-
++        self._gihelper = gihelper.GIHelper()
+ 
+     def add_packagepath(self, packagename, path):
+         """ModuleFinder can not handle __path__ modifications packages
+@@ -416,7 +420,6 @@ class ModuleFinder:
+         We also take note of 'static' global symbols in the module and
+         add them to __globalnames__.
+         """
+-
+         for what, args in self._scan_opcodes(code):
+             if what == "store":
+                 name, = args
+@@ -424,6 +427,11 @@ class ModuleFinder:
+             elif what == "import":
+                 level, fromlist, name = args
+                 self.safe_import_hook(name, mod, fromlist, level)
++            elif what == "gi_request":
++                for sharedLibrary in \
++                    self._gihelper.getSharedLibraries(args[0], args[1]):
++                    from . dllfinder import SearchPath
++                    self.add_dll(SearchPath(sharedLibrary))
+             else:
+                 # We don't expect anything else from the generator.
+                 raise RuntimeError(what)
+@@ -442,10 +450,15 @@ class ModuleFinder:
+             # dis.get_instructions() is only available in python 3.4
+             # and higher
+             instructions = []
++
++            requireCallLevel = 0
++            requiredNamespace = None
++            requiredVersion = None
+             for inst in dis.get_instructions(co):
+                 instructions.append(inst)
+                 c = inst.opcode
+                 if c == IMPORT_NAME:
++                    requireCallLevel = 0
+                     assert instructions[-3].opcode == LOAD_CONST
+                     level = instructions[-3].argval
+                     assert instructions[-2].opcode == LOAD_CONST
+@@ -453,7 +466,34 @@ class ModuleFinder:
+                     name = inst.argval
+                     yield "import", (level, fromlist, name)
+                 elif c in STORE_OPS:
++                    requireCallLevel = 0
+                     yield "store", (inst.argval,)
++                elif c == LOAD_NAME:
++                    if requireCallLevel==0 and inst.argval=="gi":
++                        requireCallLevel += 1
++                    else:
++                        requireCallLevel = 0
++                elif c == LOAD_METHOD:
++                    if requireCallLevel==1 and inst.argval=="require_version":
++                        requireCallLevel += 1
++                    else:
++                        requireCallLevel = 0
++                elif c==LOAD_CONST:
++                    if requireCallLevel==2:
++                        requiredNamespace = inst.argval
++                        requireCallLevel += 1
++                    elif requireCallLevel==3:
++                        requiredVersion = inst.argval
++                        requireCallLevel += 1
++                    else:
++                        requireCallLevel = 0
++                elif c==CALL_METHOD:
++                    if requireCallLevel==4:
++                        yield ("gi_request", (requiredNamespace, requiredVersion))
++                    requireCallLevel = 0
++                    requiredNamespace = None
++                    requiredVersion = None
++
+         else:
+             code = co.co_code
+             names = co.co_names
+diff --git a/py2exe/py2exe_distutils.py b/py2exe/py2exe_distutils.py
+index 3918849..fe97b90 100644
+--- a/py2exe/py2exe_distutils.py
++++ b/py2exe/py2exe_distutils.py
+@@ -1,5 +1,5 @@
+ # This file is only used when BUILDING py2exe.
+-import os, sys
++import os, sys, types, copy
+ 
+ from distutils.core import Extension
+ from distutils.dist import Distribution
+@@ -8,12 +8,17 @@ from distutils.sysconfig import customize_compiler
+ from distutils.dep_util import newer_group
+ from distutils.errors import DistutilsError, DistutilsSetupError, DistutilsPlatformError
+ from distutils.errors import CCompilerError, CompileError
++from distutils.file_util import write_file
+ from distutils.util import get_platform
+ from distutils import log
+ 
+-# We don't need a manifest in the executable, so monkeypatch the code away:
+-from distutils.msvc9compiler import MSVCCompiler
+-MSVCCompiler.manifest_setup_ldargs = lambda *args: None
++from distutils import ccompiler
++isMingw32 = ccompiler.get_default_compiler()=='mingw32'
++
++if not isMingw32:
++    # We don't need a manifest in the executable, so monkeypatch the code away:
++    from distutils.msvc9compiler import MSVCCompiler
++    MSVCCompiler.manifest_setup_ldargs = lambda *args: None
+ 
+ class Interpreter(Extension):
+     def __init__(self, *args, **kw):
+@@ -38,6 +43,82 @@ class Dist(Distribution):
+     def has_extensions(self):
+         return False
+ 
++def mingw32_link(self, target_desc, objects, output_filename, output_dir=None,
++             libraries=None, library_dirs=None, runtime_library_dirs=None,
++             export_symbols=None, debug=0, extra_preargs=None,
++             extra_postargs=None, build_temp=None, target_lang=None):
++    """Link the objects."""
++    from distutils.unixccompiler import UnixCCompiler
++
++    # use separate copies, so we can modify the lists
++    extra_preargs = copy.copy(extra_preargs or [])
++    libraries = copy.copy(libraries or [])
++    objects = copy.copy(objects or [])
++
++    # Additional libraries
++    libraries.extend(self.dll_libraries)
++
++    # handle export symbols by creating a def-file
++    # with executables this only works with gcc/ld as linker
++    if ((export_symbols is not None) and
++        (target_desc != self.EXECUTABLE or self.linker_dll == "gcc")):
++        # (The linker doesn't do anything if output is up-to-date.
++        # So it would probably better to check if we really need this,
++        # but for this we had to insert some unchanged parts of
++        # UnixCCompiler, and this is not what we want.)
++
++        # we want to put some files in the same directory as the
++        # object files are, build_temp doesn't help much
++        # where are the object files
++        temp_dir = os.path.dirname(objects[0])
++        # name of dll to give the helper files the same base name
++        (dll_name, dll_extension) = os.path.splitext(
++            os.path.basename(output_filename))
++
++        # generate the filenames for these files
++        def_file = os.path.join(temp_dir, dll_name + ".def")
++        lib_file = os.path.join(temp_dir, 'lib' + dll_name + ".a")
++
++        # Generate .def file
++        contents = ["EXPORTS"]
++        for sym in export_symbols:
++            contents.append(sym)
++        self.execute(write_file, (def_file, contents),
++                     "writing %s" % def_file)
++
++        # next add options for def-file and to creating import libraries
++
++        # dllwrap uses different options than gcc/ld
++        if self.linker_dll == "dllwrap":
++            extra_preargs.extend(["--output-lib", lib_file])
++            # for dllwrap we have to use a special option
++            extra_preargs.extend(["--def", def_file])
++            # we use gcc/ld here and can be sure ld is >= 2.9.10
++        else:
++            # doesn't work: bfd_close build\...\libfoo.a: Invalid operation
++            #extra_preargs.extend(["-Wl,--out-implib,%s" % lib_file])
++            # for gcc/ld the def-file is specified as any object files
++            objects.append(def_file)
++
++    #end: if ((export_symbols is not None) and
++    #        (target_desc != self.EXECUTABLE or self.linker_dll == "gcc")):
++
++    # who wants symbols and a many times larger output file
++    # should explicitly switch the debug mode on
++    # otherwise we let dllwrap/ld strip the output file
++    # (On my machine: 10KiB < stripped_file < ??100KiB
++    #   unstripped_file = stripped_file + XXX KiB
++    #  ( XXX=254 for a typical python extension))
++    if not debug and not hasattr(sys, 'gettotalrefcount'):
++        extra_preargs.append("-s")
++
++    UnixCCompiler.link(self, target_desc, objects, output_filename,
++                       output_dir, libraries, library_dirs,
++                       runtime_library_dirs,
++                       None, # export_symbols, we do this in our def-file
++                       debug, extra_preargs, extra_postargs, build_temp,
++                       target_lang)
++
+ class BuildInterpreters(build_ext.build_ext):
+     description = "build special python interpreter stubs"
+ 
+@@ -67,6 +148,9 @@ class BuildInterpreters(build_ext.build_ext):
+         if os.name == 'nt' and self.plat_name != get_platform():
+             self.compiler.initialize(self.plat_name)
+ 
++        if isMingw32:
++            self.compiler.link = types.MethodType(mingw32_link, self.compiler)
++
+         # And make sure that any compile/link-related options (which might
+         # come from the command-line or from the setup script) are set in
+         # that CCompiler object -- that way, they automatically apply to
+@@ -190,7 +274,7 @@ class BuildInterpreters(build_ext.build_ext):
+                            libraries=self.get_libraries(ext),
+                            library_dirs=ext.library_dirs,
+                            runtime_library_dirs=ext.runtime_library_dirs,
+-                           export_symbols=ext.export_symbols,
++                           export_symbols=ext.export_symbols if ext.export_symbols else None,
+                            extra_postargs=extra_args,
+                            debug=self.debug)
+ 
+diff --git a/py2exe/runtime.py b/py2exe/runtime.py
+index 10b0fa9..d154ff7 100644
+--- a/py2exe/runtime.py
++++ b/py2exe/runtime.py
+@@ -19,8 +19,8 @@ from .icons import BuildIcons
+ 
+ logger = logging.getLogger("runtime")
+ 
+-#from importlib.machinery import EXTENSION_SUFFIXES
+-EXTENSION_SUFFIXES = ['.pyd']
++from importlib.machinery import EXTENSION_SUFFIXES
++#EXTENSION_SUFFIXES = ['.pyd']
+ from importlib.machinery import DEBUG_BYTECODE_SUFFIXES, OPTIMIZED_BYTECODE_SUFFIXES
+ 
+ RT_MANIFEST = 24
+@@ -248,12 +248,15 @@ class Runtime(object):
+             if os.path.isfile(libpath):
+                 os.remove(libpath)
+ 
+-            if not os.path.exists(os.path.dirname(libpath)):
+-                os.mkdir(os.path.dirname(libpath))
+-
+-            dll_bytes = pkgutil.get_data("py2exe", "resources.dll")
+-            with open(libpath, "wb") as ofi:
+-                  ofi.write(dll_bytes)
++            if self.options.skip_archive:
++                if not os.path.exists(libpath):
++                    os.makedirs(libpath)
++            else:
++                if not os.path.exists(os.path.dirname(libpath)):
++                    os.mkdir(os.path.dirname(libpath))
++                dll_bytes = pkgutil.get_data("py2exe", "resources.dll")
++                with open(libpath, "wb") as ofi:
++                    ofi.write(dll_bytes)
+             if options.verbose:
+                 print("Building shared code archive '%s'." % libpath)
+             # Archive is appended to resources.dll; remove the icon
+@@ -263,7 +266,7 @@ class Runtime(object):
+ 
+         self.copy_files(destdir)
+ 
+-        # data directories from modulefinder
++        # data directories from modulefinder
+         for name, (src, recursive) in self.mf._data_directories.items():
+             if recursive:
+                 dst = os.path.join(destdir, name)
+@@ -274,11 +277,11 @@ class Runtime(object):
+             else:
+                 raise RuntimeError("not yet supported")
+ 
+-        # data files from modulefinder
+-        for name, src in self.mf._data_files.items():
+-            dst = os.path.join(destdir, name)
+-            shutil.copy2(src, dst)
+-
++        # data files from modulefinder
++        for name, src in self.mf._data_files.items():
++            dst = os.path.join(destdir, name)
++            shutil.copy2(src, dst)
++
+         # other data files
+         if self.options.data_files:
+             for subdir, files in self.options.data_files:
+@@ -410,46 +413,38 @@ class Runtime(object):
+             compression = zipfile.ZIP_STORED
+ 
+         # Create a zipfile and append it to the library file
+-        arc = zipfile.ZipFile(libpath, "a",
+-                              compression=compression)
+-
+-        # The same modules may be in self.ms.modules under different
+-        # keys; we only need one of them in the archive.
+-        for mod in set(self.mf.modules.values()):
+-            if mod.__code__:
+-                if hasattr(mod, "__path__"):
+-                    path = mod.__name__.replace(".", "\\") + "\\__init__" + bytecode_suffix
+-                else:
+-                    path = mod.__name__.replace(".", "\\") + bytecode_suffix
+-                stream = io.BytesIO()
+-                stream.write(imp.get_magic())
+-                if sys.version_info >= (3,7,0):
+-                    stream.write(b"\0\0\0\0") # null flags
+-                stream.write(b"\0\0\0\0") # null timestamp
+-                stream.write(b"\0\0\0\0") # null size
+-                marshal.dump(mod.__code__, stream)
+-                arc.writestr(path, stream.getvalue())
+-
+-            elif hasattr(mod, "__file__"):
+-                #assert mod.__file__.endswith(EXTENSION_SUFFIXES[0])
+-                if self.options.bundle_files <= 2:
+-                    # put .pyds into the archive
+-                    arcfnm = mod.__name__.replace(".", "\\") + EXTENSION_SUFFIXES[0]
+-                    if self.options.verbose > 1:
+-                        print("Add %s to %s" % (os.path.basename(mod.__file__), libpath))
+-                    arc.write(mod.__file__, arcfnm)
+-                else:
+-                    # The extension modules will be copied into
+-                    # dlldir.  To be able to import it without dlldir
+-                    # being on sys.path, create a loader module and
+-                    # put that into the archive.
+-                    pydfile = mod.__name__ + EXTENSION_SUFFIXES[0]
+-                    if self.options.verbose > 1:
+-                        print("Add Loader for %s to %s" % (os.path.basename(mod.__file__), libpath))
+-                    loader = LOAD_FROM_DIR.format(pydfile)
+-
+-                    code = compile(loader, "<loader>", "exec",
+-                                   optimize=self.options.optimize)
++        if self.options.skip_archive:
++            for mod in set(self.mf.modules.values()):
++                if hasattr(mod, "__file__"):
++                    path = os.path.join(*mod.__name__.split("."))
++                    if hasattr(mod, "__path__"):
++                        path = os.path.join(path, "__init__")
++                    path += bytecode_suffix if mod.__code__ else EXTENSION_SUFFIXES[0]
++                    path = os.path.join(libpath, path)
++                    dirpath = os.path.dirname(path)
++                    if not os.path.isdir(dirpath):
++                        os.makedirs(dirpath)
++                    if mod.__code__:
++                        with open(mod.__file__, "rt") as fin:
++                            code = compile(fin.read(), mod.__file__, "exec",
++                                           optimize=self.options.optimize)
++                        with open(path, "wb") as fout:
++                            fout.write(imp.get_magic())
++                            if sys.version_info >= (3,7,0):
++                                fout.write(b"\0\0\0\0") # null flags
++                            fout.write(b"\0\0\0\0") # null timestamp
++                            fout.write(b"\0\0\0\0") # null size
++                            marshal.dump(code, fout)
++                    else:
++                        shutil.copy2(mod.__file__, path)
++        else:
++            arc = zipfile.ZipFile(libpath, "a",
++                                  compression=compression)
++
++            # The same modules may be in self.ms.modules under different
++            # keys; we only need one of them in the archive.
++            for mod in set(self.mf.modules.values()):
++                if mod.__code__:
+                     if hasattr(mod, "__path__"):
+                         path = mod.__name__.replace(".", "\\") + "\\__init__" + bytecode_suffix
+                     else:
+@@ -457,28 +452,61 @@ class Runtime(object):
+                     stream = io.BytesIO()
+                     stream.write(imp.get_magic())
+                     if sys.version_info >= (3,7,0):
+-                        stream.write(b"\0\0\0\0") # null flags
++                        stream.write(b"\0\0\0\0") # null flags
+                     stream.write(b"\0\0\0\0") # null timestamp
+                     stream.write(b"\0\0\0\0") # null size
+-                    marshal.dump(code, stream)
++                    marshal.dump(mod.__code__, stream)
+                     arc.writestr(path, stream.getvalue())
+ 
+-        if self.options.bundle_files == 0:
+-            # put everything into the arc
+-            files = self.mf.all_dlls()
+-        elif self.options.bundle_files in (1, 2):
+-            # put only extension dlls into the arc
+-            files = self.mf.extension_dlls()
+-        else:
+-            arc.close()
+-            return
++                elif hasattr(mod, "__file__"):
++                    #assert mod.__file__.endswith(EXTENSION_SUFFIXES[0])
++                    if self.options.bundle_files <= 2:
++                        # put .pyds into the archive
++                        arcfnm = mod.__name__.replace(".", "\\") + EXTENSION_SUFFIXES[0]
++                        if self.options.verbose > 1:
++                            print("Add %s to %s" % (os.path.basename(mod.__file__), libpath))
++                        arc.write(mod.__file__, arcfnm)
++                    else:
++                        # The extension modules will be copied into
++                        # dlldir.  To be able to import it without dlldir
++                        # being on sys.path, create a loader module and
++                        # put that into the archive.
++                        pydfile = mod.__name__ + EXTENSION_SUFFIXES[0]
++                        if self.options.verbose > 1:
++                            print("Add Loader for %s to %s" % (os.path.basename(mod.__file__), libpath))
++                        loader = LOAD_FROM_DIR.format(pydfile)
++
++                        code = compile(loader, "<loader>", "exec",
++                                       optimize=self.options.optimize)
++                        if hasattr(mod, "__path__"):
++                            path = mod.__name__.replace(".", "\\") + "\\__init__" + bytecode_suffix
++                        else:
++                            path = mod.__name__.replace(".", "\\") + bytecode_suffix
++                        stream = io.BytesIO()
++                        stream.write(imp.get_magic())
++                        if sys.version_info >= (3,7,0):
++                            stream.write(b"\0\0\0\0") # null flags
++                        stream.write(b"\0\0\0\0") # null timestamp
++                        stream.write(b"\0\0\0\0") # null size
++                        marshal.dump(code, stream)
++                        arc.writestr(path, stream.getvalue())
++
++            if self.options.bundle_files == 0:
++                # put everything into the arc
++                files = self.mf.all_dlls()
++            elif self.options.bundle_files in (1, 2):
++                # put only extension dlls into the arc
++                files = self.mf.extension_dlls()
++            else:
++                arc.close()
++                return
+ 
+-        for src in files:
+-            if self.options.verbose > 1:
+-                print("Add DLL %s to %s" % (os.path.basename(src), libpath))
+-            arc.write(src, os.path.basename(src))
++            for src in files:
++                if self.options.verbose > 1:
++                    print("Add DLL %s to %s" % (os.path.basename(src), libpath))
++                arc.write(src, os.path.basename(src))
+ 
+-        arc.close()
++            arc.close()
+ 
+     def copy_files(self, destdir):
+         """Copy files (pyds, dlls, depending on the bundle_files value,
+@@ -498,17 +526,19 @@ class Runtime(object):
+             with UpdateResources(dst, delete_existing=False) as resource:
+                 resource.add_string(1000, "py2exe")
+ 
+-        if self.options.bundle_files == 3:
++        if not self.options.skip_archive and self.options.bundle_files == 3:
+             # copy extension modules; they go to libdir
+             for mod in self.mf.modules.values():
+                 if mod.__code__:
+                     # nothing to do for python modules.
+                     continue
+                 if hasattr(mod, "__file__"):
+-                    assert mod.__file__.endswith(EXTENSION_SUFFIXES[0])
+-                    pydfile = mod.__name__ + EXTENSION_SUFFIXES[0]
++                    if mod.__file__.endswith(EXTENSION_SUFFIXES[0]):
++                        pydfile = mod.__name__ + EXTENSION_SUFFIXES[0]
+ 
+-                    dst = os.path.join(libdir, pydfile)
++                        dst = os.path.join(libdir, pydfile)
++                    else:
++                        dst = os.path.join(libdir, os.path.basename(mod.__file__))
+                     if self.options.verbose:
+                         print("Copy %s to %s" % (mod.__file__, dst))
+                     shutil.copy2(mod.__file__, dst)
+@@ -638,9 +668,11 @@ def __load():
+     dllpath = os.path.join(os.path.dirname(__loader__.archive), r'{0}')
+     try:
+         mod = imp.load_dynamic(__name__, dllpath)
++        mod.frozen = 1
+     except ImportError as details:
+         raise ImportError('(%s) %r' % (details, dllpath)) from None
+-    mod.frozen = 1
++    except AttributeError:
++        pass
+ __load()
+ del __load
+ """
+diff --git a/setup.py b/setup.py
+index 342d194..5fb5a9a 100644
+--- a/setup.py
++++ b/setup.py
+@@ -12,6 +12,8 @@ if sys.version_info < (3, 3):
+ ############################################################################
+ 
+ from setuptools import setup
++from distutils import ccompiler
++isMingw32 = ccompiler.get_default_compiler()=='mingw32'
+ ##from distutils.core import setup
+ 
+ from py2exe.py2exe_distutils import Dist, Interpreter, BuildInterpreters
+@@ -26,11 +28,11 @@ def _is_debug_build():
+     return False
+ 
+ if _is_debug_build():
+-    macros = [("PYTHONDLL", '\\"python%d%d_d.dll\\"' % sys.version_info[:2]),
++    macros = [("PYTHONDLL", ('"libpython%d.%dm_d.dll"' if isMingw32 else '"\\python%d%d_d.dll\\"') % sys.version_info[:2]),
+ ##              ("PYTHONCOM", '\\"pythoncom%d%d_d.dll\\"' % sys.version_info[:2]),
+               ("_CRT_SECURE_NO_WARNINGS", '1')]
+ else:
+-    macros = [("PYTHONDLL", '\\"python%d%d.dll\\"' % sys.version_info[:2]),
++    macros = [("PYTHONDLL", ('"libpython%d.%dm.dll"' if isMingw32 else '"\\python%d%d.dll\\"') % sys.version_info[:2]),
+ ##              ("PYTHONCOM", '\\"pythoncom%d%d.dll\\"' % sys.version_info[:2]),
+               ("_CRT_SECURE_NO_WARNINGS", '1'),]
+ 
+@@ -39,9 +41,10 @@ macros.append(("Py_BUILD_CORE", '1'))
+ extra_compile_args = []
+ extra_link_args = []
+ 
+-extra_compile_args.append("-IC:\\Program Files\\Microsoft SDKs\\Windows\\v7.0\\Include")
+-extra_compile_args.append("-IC:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\VC\\include")
+-extra_compile_args.append("-IC:\\Program Files (x86)\\Windows Kits\\10\\Include\\10.0.10586.0\\ucrt")
++if not isMingw32:
++    extra_compile_args.append("-IC:\\Program Files\\Microsoft SDKs\\Windows\\v7.0\\Include")
++    extra_compile_args.append("-IC:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\VC\\include")
++    extra_compile_args.append("-IC:\\Program Files (x86)\\Windows Kits\\10\\Include\\10.0.10586.0\\ucrt")
+ 
+ if 0:
+     # enable this to debug a release build
+@@ -63,7 +66,11 @@ run_ctypes_dll = Interpreter("py2exe.run_ctypes_dll",
+                               "source/python-dynload.c",
+                               ],
+                              libraries=["user32", "shell32"],
+-                             export_symbols=["DllCanUnloadNow,PRIVATE",
++                             export_symbols=["DllCanUnloadNow",
++                                             "DllGetClassObject",
++                                             "DllRegisterServer",
++                                             "DllUnregisterServer",
++                                             ] if isMingw32 else ["DllCanUnloadNow,PRIVATE",
+                                              "DllGetClassObject,PRIVATE",
+                                              "DllRegisterServer,PRIVATE",
+                                              "DllUnregisterServer,PRIVATE",
+@@ -71,7 +78,7 @@ run_ctypes_dll = Interpreter("py2exe.run_ctypes_dll",
+                              target_desc = "shared_library",
+                              define_macros=macros,
+                              extra_compile_args=extra_compile_args,
+-                             extra_link_args=extra_link_args + ["/DLL"],
++                             extra_link_args=extra_link_args + ([] if isMingw32 else ["/DLL"]),
+                              )
+ 
+ run = Interpreter("py2exe.run",
+@@ -123,7 +130,7 @@ resource_dll = Interpreter("py2exe.resources",
+                            ["source/dll.c",
+                             "source/icon.rc"],
+                            target_desc = "shared_library",
+-                           extra_link_args=["/DLL"],
++                           extra_link_args=[] if isMingw32 else ["/DLL"],
+                            )
+ 
+ interpreters = [run, run_w, resource_dll,
+diff --git a/source/python-dynload.c b/source/python-dynload.c
+index 2a60b86..373bb62 100644
+--- a/source/python-dynload.c
++++ b/source/python-dynload.c
+@@ -31,7 +31,7 @@ static HMODULE hmod_pydll;
+ 
+ #define FUNC(res, name, args) \
+   static res(*proc)args; \
+-  if (!proc) (FARPROC)proc = MyGetProcAddress(hmod_pydll, #name)
++  if (!proc) proc = (res (*)args)MyGetProcAddress(hmod_pydll, #name)
+ 
+ #define DATA(type, name)				\
+   static type pflag; \
+@@ -158,7 +158,7 @@ void PyErr_Print(void)
+   proc();
+ }
+ 
+-void Py_SetProgramName(wchar_t *name)
++void Py_SetProgramName(const wchar_t *name)
+ {
+   FUNC(void, Py_SetProgramName, (wchar_t *));
+   proc(name);
+diff --git a/source/run.c b/source/run.c
+index e1f630e..933ae77 100644
+--- a/source/run.c
++++ b/source/run.c
+@@ -54,7 +54,11 @@ extern int start(int argc, wchar_t **argv);
+ /*
+   The main function for our exe.
+ */
++#if defined(__MINGW32__)
++int main (int argc, wchar_t **argv)
++#else
+ int wmain (int argc, wchar_t **argv)
++#endif
+ {
+ 	int result;
+ 	result = init("console_exe");
+diff --git a/source/start.c b/source/start.c
+index e894ae6..6b61624 100644
+--- a/source/start.c
++++ b/source/start.c
+@@ -128,7 +128,7 @@ BOOL locate_script(HMODULE hmod)
+ 		SystemError(GetLastError(), "Could not load script resource:");
+ 		return FALSE;
+ 	}
+-	p_script_info = (struct scriptinfo *)pScript = LockResource(hgbl);
++	p_script_info = (struct scriptinfo *)(pScript = LockResource(hgbl));
+ 	if (!pScript)  {
+ 		SystemError(GetLastError(), "Could not lock script resource:");
+ 		return FALSE;
+diff --git a/setup.py b/setup.py
+index 342d194..1fe1e43 100644
+--- a/setup.py
++++ b/setup.py
+@@ -107,7 +107,7 @@ run_w = Interpreter("py2exe.run_w",
+                     libraries=["user32", "shell32"],
+                     define_macros=macros,
+                     extra_compile_args=extra_compile_args,
+-                    extra_link_args=extra_link_args,
++                    extra_link_args=extra_link_args + (["-Wl,--subsystem,windows"] if isMingw32 else []),
+                     )
+ 
+ # The py2exe.resources name is special handled in BuildInterpreters;
Index: docker/msys/py2exe.patch
===================================================================
--- docker/msys/py2exe.patch	(revision 936)
+++ 	(revision )
@@ -1,736 +1,0 @@
-diff --git a/py2exe/distutils_buildexe.py b/py2exe/distutils_buildexe.py
-index ae8aca3..d809641 100644
---- a/py2exe/distutils_buildexe.py
-+++ b/py2exe/distutils_buildexe.py
-@@ -154,6 +154,7 @@ class py2exe(Command):
-         self.ascii = 0
-         self.custom_boot_script = None
-         self.use_assembly = False
-+        self.gi_namespaces = []
- 
-     def finalize_options (self):
-         self.optimize = int(self.optimize)
-@@ -239,6 +240,7 @@ class py2exe(Command):
-                             excludes = self.excludes,
-                             ignores = self.ignores,
-                             packages = self.packages,
-+                            gi_namespaces = self.gi_namespaces,
-                             dist_dist = self.dist_dir,
-                             dll_excludes = self.dll_excludes,
-                             typelibs = self.typelibs,
-diff --git a/py2exe/dllfinder.py b/py2exe/dllfinder.py
-index 4e5e76c..bb43f9e 100644
---- a/py2exe/dllfinder.py
-+++ b/py2exe/dllfinder.py
-@@ -68,7 +68,8 @@ class DllFinder:
-             if dll in self._loaded_dlls:
-                 continue
-             for dep_dll in self.bind_image(dll):
--                if dep_dll in self._loaded_dlls:
-+                bname = os.path.basename(dep_dll).lower()
-+                if bname in self._loaded_dlls:
-                     continue
-                 dll_type = self.determine_dll_type(dep_dll)
-                 if dll_type is None:
-@@ -144,7 +145,8 @@ class DllFinder:
-         deps = self.bind_image(imagename)
-         if pydll in [d.lower() for d in deps]:
-             return "EXT"
--        if fnm.startswith(windir + os.sep) or fnm.startswith(sysdir + os.sep):
-+        if fnm.startswith(windir + os.sep) or fnm.startswith(sysdir + os.sep) or \
-+           fnm.startswith(windir + '\\') or fnm.startswith(sysdir + '\\'):
-             return None
-         return "DLL"
- 
-diff --git a/py2exe/gihelper.py b/py2exe/gihelper.py
-index e69de29..f597692 100644
---- a/py2exe/gihelper.py
-+++ b/py2exe/gihelper.py
-@@ -0,0 +1,58 @@
-+
-+import cffi
-+
-+class GIHelper(object):
-+    _cdef="""
-+        typedef char gchar;
-+        typedef int gint;
-+        typedef uint32_t guint32;
-+        typedef guint32 GQuark;
-+
-+        typedef struct {
-+          GQuark    domain;
-+          gint      code;
-+          gchar     *message;
-+        } GError;
-+
-+        typedef struct _GITypelib GITypelib;
-+        typedef struct _GIRepository         GIRepository;
-+
-+        typedef enum
-+        {
-+          G_IREPOSITORY_LOAD_FLAG_LAZY = 1
-+        } GIRepositoryLoadFlags;
-+
-+        GIRepository *g_irepository_get_default   (void);
-+
-+        GITypelib *    g_irepository_require       (GIRepository *repository,
-+                               const gchar  *namespace_,
-+                               const gchar  *version,
-+                               GIRepositoryLoadFlags flags,
-+                               GError      **error);
-+
-+        const gchar * g_irepository_get_shared_library (GIRepository *repository,
-+                                const gchar  *namespace_);
-+        """
-+
-+    def __init__(self):
-+        self._ffi = cffi.FFI()
-+        self._ffi.cdef(self._cdef)
-+
-+        self._lib = self._ffi.dlopen("libgirepository-1.0-1.dll")
-+
-+        self._repo=self._lib.g_irepository_get_default()
-+
-+        self._error = self._ffi.new("GError**")
-+
-+    def getSharedLibraries(self, namespace, version):
-+        typelib = self._lib.g_irepository_require(self._repo,
-+                                        bytes(namespace, "utf-8"),
-+                                        bytes(version, "utf-8"),
-+                                        0, self._error)
-+        if typelib == self._ffi.NULL:
-+            return []
-+        else:
-+            return str(
-+                self._ffi.string(
-+                    self._lib.g_irepository_get_shared_library(
-+                        self._repo, bytes(namespace, "utf-8"))), "utf-8").split(",")
-diff --git a/py2exe/mf3.py b/py2exe/mf3.py
-index f645740..ec1f261 100644
---- a/py2exe/mf3.py
-+++ b/py2exe/mf3.py
-@@ -5,6 +5,7 @@
- 
- # XXX XXX XXX Does not yet support PEP 452 namespace packages!
- 
-+from . import gihelper
- from collections import defaultdict
- import dis
- import importlib
-@@ -21,6 +22,9 @@ LOAD_CONST = dis.opname.index('LOAD_CONST')
- IMPORT_NAME = dis.opname.index('IMPORT_NAME')
- STORE_NAME = dis.opname.index('STORE_NAME')
- STORE_GLOBAL = dis.opname.index('STORE_GLOBAL')
-+LOAD_NAME = dis.opname.index('LOAD_NAME')
-+LOAD_METHOD = dis.opname.index('LOAD_METHOD')
-+CALL_METHOD = dis.opname.index('CALL_METHOD')
- STORE_OPS = [STORE_NAME, STORE_GLOBAL]
- HAVE_ARGUMENT = dis.HAVE_ARGUMENT
- 
-@@ -63,7 +67,7 @@ class ModuleFinder:
-         self._depgraph = defaultdict(set)
-         self._indent = ""
-         self._package_paths = defaultdict(list)
--
-+        self._gihelper = gihelper.GIHelper()
- 
-     def add_packagepath(self, packagename, path):
-         """ModuleFinder can not handle __path__ modifications packages
-@@ -416,7 +420,6 @@ class ModuleFinder:
-         We also take note of 'static' global symbols in the module and
-         add them to __globalnames__.
-         """
--
-         for what, args in self._scan_opcodes(code):
-             if what == "store":
-                 name, = args
-@@ -424,6 +427,11 @@ class ModuleFinder:
-             elif what == "import":
-                 level, fromlist, name = args
-                 self.safe_import_hook(name, mod, fromlist, level)
-+            elif what == "gi_request":
-+                for sharedLibrary in \
-+                    self._gihelper.getSharedLibraries(args[0], args[1]):
-+                    from . dllfinder import SearchPath
-+                    self.add_dll(SearchPath(sharedLibrary))
-             else:
-                 # We don't expect anything else from the generator.
-                 raise RuntimeError(what)
-@@ -442,10 +450,15 @@ class ModuleFinder:
-             # dis.get_instructions() is only available in python 3.4
-             # and higher
-             instructions = []
-+
-+            requireCallLevel = 0
-+            requiredNamespace = None
-+            requiredVersion = None
-             for inst in dis.get_instructions(co):
-                 instructions.append(inst)
-                 c = inst.opcode
-                 if c == IMPORT_NAME:
-+                    requireCallLevel = 0
-                     assert instructions[-3].opcode == LOAD_CONST
-                     level = instructions[-3].argval
-                     assert instructions[-2].opcode == LOAD_CONST
-@@ -453,7 +466,34 @@ class ModuleFinder:
-                     name = inst.argval
-                     yield "import", (level, fromlist, name)
-                 elif c in STORE_OPS:
-+                    requireCallLevel = 0
-                     yield "store", (inst.argval,)
-+                elif c == LOAD_NAME:
-+                    if requireCallLevel==0 and inst.argval=="gi":
-+                        requireCallLevel += 1
-+                    else:
-+                        requireCallLevel = 0
-+                elif c == LOAD_METHOD:
-+                    if requireCallLevel==1 and inst.argval=="require_version":
-+                        requireCallLevel += 1
-+                    else:
-+                        requireCallLevel = 0
-+                elif c==LOAD_CONST:
-+                    if requireCallLevel==2:
-+                        requiredNamespace = inst.argval
-+                        requireCallLevel += 1
-+                    elif requireCallLevel==3:
-+                        requiredVersion = inst.argval
-+                        requireCallLevel += 1
-+                    else:
-+                        requireCallLevel = 0
-+                elif c==CALL_METHOD:
-+                    if requireCallLevel==4:
-+                        yield ("gi_request", (requiredNamespace, requiredVersion))
-+                    requireCallLevel = 0
-+                    requiredNamespace = None
-+                    requiredVersion = None
-+
-         else:
-             code = co.co_code
-             names = co.co_names
-diff --git a/py2exe/py2exe_distutils.py b/py2exe/py2exe_distutils.py
-index 3918849..fe97b90 100644
---- a/py2exe/py2exe_distutils.py
-+++ b/py2exe/py2exe_distutils.py
-@@ -1,5 +1,5 @@
- # This file is only used when BUILDING py2exe.
--import os, sys
-+import os, sys, types, copy
- 
- from distutils.core import Extension
- from distutils.dist import Distribution
-@@ -8,12 +8,17 @@ from distutils.sysconfig import customize_compiler
- from distutils.dep_util import newer_group
- from distutils.errors import DistutilsError, DistutilsSetupError, DistutilsPlatformError
- from distutils.errors import CCompilerError, CompileError
-+from distutils.file_util import write_file
- from distutils.util import get_platform
- from distutils import log
- 
--# We don't need a manifest in the executable, so monkeypatch the code away:
--from distutils.msvc9compiler import MSVCCompiler
--MSVCCompiler.manifest_setup_ldargs = lambda *args: None
-+from distutils import ccompiler
-+isMingw32 = ccompiler.get_default_compiler()=='mingw32'
-+
-+if not isMingw32:
-+    # We don't need a manifest in the executable, so monkeypatch the code away:
-+    from distutils.msvc9compiler import MSVCCompiler
-+    MSVCCompiler.manifest_setup_ldargs = lambda *args: None
- 
- class Interpreter(Extension):
-     def __init__(self, *args, **kw):
-@@ -38,6 +43,82 @@ class Dist(Distribution):
-     def has_extensions(self):
-         return False
- 
-+def mingw32_link(self, target_desc, objects, output_filename, output_dir=None,
-+             libraries=None, library_dirs=None, runtime_library_dirs=None,
-+             export_symbols=None, debug=0, extra_preargs=None,
-+             extra_postargs=None, build_temp=None, target_lang=None):
-+    """Link the objects."""
-+    from distutils.unixccompiler import UnixCCompiler
-+
-+    # use separate copies, so we can modify the lists
-+    extra_preargs = copy.copy(extra_preargs or [])
-+    libraries = copy.copy(libraries or [])
-+    objects = copy.copy(objects or [])
-+
-+    # Additional libraries
-+    libraries.extend(self.dll_libraries)
-+
-+    # handle export symbols by creating a def-file
-+    # with executables this only works with gcc/ld as linker
-+    if ((export_symbols is not None) and
-+        (target_desc != self.EXECUTABLE or self.linker_dll == "gcc")):
-+        # (The linker doesn't do anything if output is up-to-date.
-+        # So it would probably better to check if we really need this,
-+        # but for this we had to insert some unchanged parts of
-+        # UnixCCompiler, and this is not what we want.)
-+
-+        # we want to put some files in the same directory as the
-+        # object files are, build_temp doesn't help much
-+        # where are the object files
-+        temp_dir = os.path.dirname(objects[0])
-+        # name of dll to give the helper files the same base name
-+        (dll_name, dll_extension) = os.path.splitext(
-+            os.path.basename(output_filename))
-+
-+        # generate the filenames for these files
-+        def_file = os.path.join(temp_dir, dll_name + ".def")
-+        lib_file = os.path.join(temp_dir, 'lib' + dll_name + ".a")
-+
-+        # Generate .def file
-+        contents = ["EXPORTS"]
-+        for sym in export_symbols:
-+            contents.append(sym)
-+        self.execute(write_file, (def_file, contents),
-+                     "writing %s" % def_file)
-+
-+        # next add options for def-file and to creating import libraries
-+
-+        # dllwrap uses different options than gcc/ld
-+        if self.linker_dll == "dllwrap":
-+            extra_preargs.extend(["--output-lib", lib_file])
-+            # for dllwrap we have to use a special option
-+            extra_preargs.extend(["--def", def_file])
-+            # we use gcc/ld here and can be sure ld is >= 2.9.10
-+        else:
-+            # doesn't work: bfd_close build\...\libfoo.a: Invalid operation
-+            #extra_preargs.extend(["-Wl,--out-implib,%s" % lib_file])
-+            # for gcc/ld the def-file is specified as any object files
-+            objects.append(def_file)
-+
-+    #end: if ((export_symbols is not None) and
-+    #        (target_desc != self.EXECUTABLE or self.linker_dll == "gcc")):
-+
-+    # who wants symbols and a many times larger output file
-+    # should explicitly switch the debug mode on
-+    # otherwise we let dllwrap/ld strip the output file
-+    # (On my machine: 10KiB < stripped_file < ??100KiB
-+    #   unstripped_file = stripped_file + XXX KiB
-+    #  ( XXX=254 for a typical python extension))
-+    if not debug and not hasattr(sys, 'gettotalrefcount'):
-+        extra_preargs.append("-s")
-+
-+    UnixCCompiler.link(self, target_desc, objects, output_filename,
-+                       output_dir, libraries, library_dirs,
-+                       runtime_library_dirs,
-+                       None, # export_symbols, we do this in our def-file
-+                       debug, extra_preargs, extra_postargs, build_temp,
-+                       target_lang)
-+
- class BuildInterpreters(build_ext.build_ext):
-     description = "build special python interpreter stubs"
- 
-@@ -67,6 +148,9 @@ class BuildInterpreters(build_ext.build_ext):
-         if os.name == 'nt' and self.plat_name != get_platform():
-             self.compiler.initialize(self.plat_name)
- 
-+        if isMingw32:
-+            self.compiler.link = types.MethodType(mingw32_link, self.compiler)
-+
-         # And make sure that any compile/link-related options (which might
-         # come from the command-line or from the setup script) are set in
-         # that CCompiler object -- that way, they automatically apply to
-@@ -190,7 +274,7 @@ class BuildInterpreters(build_ext.build_ext):
-                            libraries=self.get_libraries(ext),
-                            library_dirs=ext.library_dirs,
-                            runtime_library_dirs=ext.runtime_library_dirs,
--                           export_symbols=ext.export_symbols,
-+                           export_symbols=ext.export_symbols if ext.export_symbols else None,
-                            extra_postargs=extra_args,
-                            debug=self.debug)
- 
-diff --git a/py2exe/runtime.py b/py2exe/runtime.py
-index 10b0fa9..d154ff7 100644
---- a/py2exe/runtime.py
-+++ b/py2exe/runtime.py
-@@ -19,8 +19,8 @@ from .icons import BuildIcons
- 
- logger = logging.getLogger("runtime")
- 
--#from importlib.machinery import EXTENSION_SUFFIXES
--EXTENSION_SUFFIXES = ['.pyd']
-+from importlib.machinery import EXTENSION_SUFFIXES
-+#EXTENSION_SUFFIXES = ['.pyd']
- from importlib.machinery import DEBUG_BYTECODE_SUFFIXES, OPTIMIZED_BYTECODE_SUFFIXES
- 
- RT_MANIFEST = 24
-@@ -248,12 +248,15 @@ class Runtime(object):
-             if os.path.isfile(libpath):
-                 os.remove(libpath)
- 
--            if not os.path.exists(os.path.dirname(libpath)):
--                os.mkdir(os.path.dirname(libpath))
--
--            dll_bytes = pkgutil.get_data("py2exe", "resources.dll")
--            with open(libpath, "wb") as ofi:
--                  ofi.write(dll_bytes)
-+            if self.options.skip_archive:
-+                if not os.path.exists(libpath):
-+                    os.makedirs(libpath)
-+            else:
-+                if not os.path.exists(os.path.dirname(libpath)):
-+                    os.mkdir(os.path.dirname(libpath))
-+                dll_bytes = pkgutil.get_data("py2exe", "resources.dll")
-+                with open(libpath, "wb") as ofi:
-+                    ofi.write(dll_bytes)
-             if options.verbose:
-                 print("Building shared code archive '%s'." % libpath)
-             # Archive is appended to resources.dll; remove the icon
-@@ -263,7 +266,7 @@ class Runtime(object):
- 
-         self.copy_files(destdir)
- 
--        # data directories from modulefinder
-+        # data directories from modulefinder
-         for name, (src, recursive) in self.mf._data_directories.items():
-             if recursive:
-                 dst = os.path.join(destdir, name)
-@@ -274,11 +277,11 @@ class Runtime(object):
-             else:
-                 raise RuntimeError("not yet supported")
- 
--        # data files from modulefinder
--        for name, src in self.mf._data_files.items():
--            dst = os.path.join(destdir, name)
--            shutil.copy2(src, dst)
--
-+        # data files from modulefinder
-+        for name, src in self.mf._data_files.items():
-+            dst = os.path.join(destdir, name)
-+            shutil.copy2(src, dst)
-+
-         # other data files
-         if self.options.data_files:
-             for subdir, files in self.options.data_files:
-@@ -410,46 +413,38 @@ class Runtime(object):
-             compression = zipfile.ZIP_STORED
- 
-         # Create a zipfile and append it to the library file
--        arc = zipfile.ZipFile(libpath, "a",
--                              compression=compression)
--
--        # The same modules may be in self.ms.modules under different
--        # keys; we only need one of them in the archive.
--        for mod in set(self.mf.modules.values()):
--            if mod.__code__:
--                if hasattr(mod, "__path__"):
--                    path = mod.__name__.replace(".", "\\") + "\\__init__" + bytecode_suffix
--                else:
--                    path = mod.__name__.replace(".", "\\") + bytecode_suffix
--                stream = io.BytesIO()
--                stream.write(imp.get_magic())
--                if sys.version_info >= (3,7,0):
--                    stream.write(b"\0\0\0\0") # null flags
--                stream.write(b"\0\0\0\0") # null timestamp
--                stream.write(b"\0\0\0\0") # null size
--                marshal.dump(mod.__code__, stream)
--                arc.writestr(path, stream.getvalue())
--
--            elif hasattr(mod, "__file__"):
--                #assert mod.__file__.endswith(EXTENSION_SUFFIXES[0])
--                if self.options.bundle_files <= 2:
--                    # put .pyds into the archive
--                    arcfnm = mod.__name__.replace(".", "\\") + EXTENSION_SUFFIXES[0]
--                    if self.options.verbose > 1:
--                        print("Add %s to %s" % (os.path.basename(mod.__file__), libpath))
--                    arc.write(mod.__file__, arcfnm)
--                else:
--                    # The extension modules will be copied into
--                    # dlldir.  To be able to import it without dlldir
--                    # being on sys.path, create a loader module and
--                    # put that into the archive.
--                    pydfile = mod.__name__ + EXTENSION_SUFFIXES[0]
--                    if self.options.verbose > 1:
--                        print("Add Loader for %s to %s" % (os.path.basename(mod.__file__), libpath))
--                    loader = LOAD_FROM_DIR.format(pydfile)
--
--                    code = compile(loader, "<loader>", "exec",
--                                   optimize=self.options.optimize)
-+        if self.options.skip_archive:
-+            for mod in set(self.mf.modules.values()):
-+                if hasattr(mod, "__file__"):
-+                    path = os.path.join(*mod.__name__.split("."))
-+                    if hasattr(mod, "__path__"):
-+                        path = os.path.join(path, "__init__")
-+                    path += bytecode_suffix if mod.__code__ else EXTENSION_SUFFIXES[0]
-+                    path = os.path.join(libpath, path)
-+                    dirpath = os.path.dirname(path)
-+                    if not os.path.isdir(dirpath):
-+                        os.makedirs(dirpath)
-+                    if mod.__code__:
-+                        with open(mod.__file__, "rt") as fin:
-+                            code = compile(fin.read(), mod.__file__, "exec",
-+                                           optimize=self.options.optimize)
-+                        with open(path, "wb") as fout:
-+                            fout.write(imp.get_magic())
-+                            if sys.version_info >= (3,7,0):
-+                                fout.write(b"\0\0\0\0") # null flags
-+                            fout.write(b"\0\0\0\0") # null timestamp
-+                            fout.write(b"\0\0\0\0") # null size
-+                            marshal.dump(code, fout)
-+                    else:
-+                        shutil.copy2(mod.__file__, path)
-+        else:
-+            arc = zipfile.ZipFile(libpath, "a",
-+                                  compression=compression)
-+
-+            # The same modules may be in self.ms.modules under different
-+            # keys; we only need one of them in the archive.
-+            for mod in set(self.mf.modules.values()):
-+                if mod.__code__:
-                     if hasattr(mod, "__path__"):
-                         path = mod.__name__.replace(".", "\\") + "\\__init__" + bytecode_suffix
-                     else:
-@@ -457,28 +452,61 @@ class Runtime(object):
-                     stream = io.BytesIO()
-                     stream.write(imp.get_magic())
-                     if sys.version_info >= (3,7,0):
--                        stream.write(b"\0\0\0\0") # null flags
-+                        stream.write(b"\0\0\0\0") # null flags
-                     stream.write(b"\0\0\0\0") # null timestamp
-                     stream.write(b"\0\0\0\0") # null size
--                    marshal.dump(code, stream)
-+                    marshal.dump(mod.__code__, stream)
-                     arc.writestr(path, stream.getvalue())
- 
--        if self.options.bundle_files == 0:
--            # put everything into the arc
--            files = self.mf.all_dlls()
--        elif self.options.bundle_files in (1, 2):
--            # put only extension dlls into the arc
--            files = self.mf.extension_dlls()
--        else:
--            arc.close()
--            return
-+                elif hasattr(mod, "__file__"):
-+                    #assert mod.__file__.endswith(EXTENSION_SUFFIXES[0])
-+                    if self.options.bundle_files <= 2:
-+                        # put .pyds into the archive
-+                        arcfnm = mod.__name__.replace(".", "\\") + EXTENSION_SUFFIXES[0]
-+                        if self.options.verbose > 1:
-+                            print("Add %s to %s" % (os.path.basename(mod.__file__), libpath))
-+                        arc.write(mod.__file__, arcfnm)
-+                    else:
-+                        # The extension modules will be copied into
-+                        # dlldir.  To be able to import it without dlldir
-+                        # being on sys.path, create a loader module and
-+                        # put that into the archive.
-+                        pydfile = mod.__name__ + EXTENSION_SUFFIXES[0]
-+                        if self.options.verbose > 1:
-+                            print("Add Loader for %s to %s" % (os.path.basename(mod.__file__), libpath))
-+                        loader = LOAD_FROM_DIR.format(pydfile)
-+
-+                        code = compile(loader, "<loader>", "exec",
-+                                       optimize=self.options.optimize)
-+                        if hasattr(mod, "__path__"):
-+                            path = mod.__name__.replace(".", "\\") + "\\__init__" + bytecode_suffix
-+                        else:
-+                            path = mod.__name__.replace(".", "\\") + bytecode_suffix
-+                        stream = io.BytesIO()
-+                        stream.write(imp.get_magic())
-+                        if sys.version_info >= (3,7,0):
-+                            stream.write(b"\0\0\0\0") # null flags
-+                        stream.write(b"\0\0\0\0") # null timestamp
-+                        stream.write(b"\0\0\0\0") # null size
-+                        marshal.dump(code, stream)
-+                        arc.writestr(path, stream.getvalue())
-+
-+            if self.options.bundle_files == 0:
-+                # put everything into the arc
-+                files = self.mf.all_dlls()
-+            elif self.options.bundle_files in (1, 2):
-+                # put only extension dlls into the arc
-+                files = self.mf.extension_dlls()
-+            else:
-+                arc.close()
-+                return
- 
--        for src in files:
--            if self.options.verbose > 1:
--                print("Add DLL %s to %s" % (os.path.basename(src), libpath))
--            arc.write(src, os.path.basename(src))
-+            for src in files:
-+                if self.options.verbose > 1:
-+                    print("Add DLL %s to %s" % (os.path.basename(src), libpath))
-+                arc.write(src, os.path.basename(src))
- 
--        arc.close()
-+            arc.close()
- 
-     def copy_files(self, destdir):
-         """Copy files (pyds, dlls, depending on the bundle_files value,
-@@ -498,17 +526,19 @@ class Runtime(object):
-             with UpdateResources(dst, delete_existing=False) as resource:
-                 resource.add_string(1000, "py2exe")
- 
--        if self.options.bundle_files == 3:
-+        if not self.options.skip_archive and self.options.bundle_files == 3:
-             # copy extension modules; they go to libdir
-             for mod in self.mf.modules.values():
-                 if mod.__code__:
-                     # nothing to do for python modules.
-                     continue
-                 if hasattr(mod, "__file__"):
--                    assert mod.__file__.endswith(EXTENSION_SUFFIXES[0])
--                    pydfile = mod.__name__ + EXTENSION_SUFFIXES[0]
-+                    if mod.__file__.endswith(EXTENSION_SUFFIXES[0]):
-+                        pydfile = mod.__name__ + EXTENSION_SUFFIXES[0]
- 
--                    dst = os.path.join(libdir, pydfile)
-+                        dst = os.path.join(libdir, pydfile)
-+                    else:
-+                        dst = os.path.join(libdir, os.path.basename(mod.__file__))
-                     if self.options.verbose:
-                         print("Copy %s to %s" % (mod.__file__, dst))
-                     shutil.copy2(mod.__file__, dst)
-@@ -638,9 +668,11 @@ def __load():
-     dllpath = os.path.join(os.path.dirname(__loader__.archive), r'{0}')
-     try:
-         mod = imp.load_dynamic(__name__, dllpath)
-+        mod.frozen = 1
-     except ImportError as details:
-         raise ImportError('(%s) %r' % (details, dllpath)) from None
--    mod.frozen = 1
-+    except AttributeError:
-+        pass
- __load()
- del __load
- """
-diff --git a/setup.py b/setup.py
-index 342d194..5fb5a9a 100644
---- a/setup.py
-+++ b/setup.py
-@@ -12,6 +12,8 @@ if sys.version_info < (3, 3):
- ############################################################################
- 
- from setuptools import setup
-+from distutils import ccompiler
-+isMingw32 = ccompiler.get_default_compiler()=='mingw32'
- ##from distutils.core import setup
- 
- from py2exe.py2exe_distutils import Dist, Interpreter, BuildInterpreters
-@@ -26,11 +28,11 @@ def _is_debug_build():
-     return False
- 
- if _is_debug_build():
--    macros = [("PYTHONDLL", '\\"python%d%d_d.dll\\"' % sys.version_info[:2]),
-+    macros = [("PYTHONDLL", ('"libpython%d.%dm_d.dll"' if isMingw32 else '"\\python%d%d_d.dll\\"') % sys.version_info[:2]),
- ##              ("PYTHONCOM", '\\"pythoncom%d%d_d.dll\\"' % sys.version_info[:2]),
-               ("_CRT_SECURE_NO_WARNINGS", '1')]
- else:
--    macros = [("PYTHONDLL", '\\"python%d%d.dll\\"' % sys.version_info[:2]),
-+    macros = [("PYTHONDLL", ('"libpython%d.%dm.dll"' if isMingw32 else '"\\python%d%d.dll\\"') % sys.version_info[:2]),
- ##              ("PYTHONCOM", '\\"pythoncom%d%d.dll\\"' % sys.version_info[:2]),
-               ("_CRT_SECURE_NO_WARNINGS", '1'),]
- 
-@@ -39,9 +41,10 @@ macros.append(("Py_BUILD_CORE", '1'))
- extra_compile_args = []
- extra_link_args = []
- 
--extra_compile_args.append("-IC:\\Program Files\\Microsoft SDKs\\Windows\\v7.0\\Include")
--extra_compile_args.append("-IC:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\VC\\include")
--extra_compile_args.append("-IC:\\Program Files (x86)\\Windows Kits\\10\\Include\\10.0.10586.0\\ucrt")
-+if not isMingw32:
-+    extra_compile_args.append("-IC:\\Program Files\\Microsoft SDKs\\Windows\\v7.0\\Include")
-+    extra_compile_args.append("-IC:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\VC\\include")
-+    extra_compile_args.append("-IC:\\Program Files (x86)\\Windows Kits\\10\\Include\\10.0.10586.0\\ucrt")
- 
- if 0:
-     # enable this to debug a release build
-@@ -63,7 +66,11 @@ run_ctypes_dll = Interpreter("py2exe.run_ctypes_dll",
-                               "source/python-dynload.c",
-                               ],
-                              libraries=["user32", "shell32"],
--                             export_symbols=["DllCanUnloadNow,PRIVATE",
-+                             export_symbols=["DllCanUnloadNow",
-+                                             "DllGetClassObject",
-+                                             "DllRegisterServer",
-+                                             "DllUnregisterServer",
-+                                             ] if isMingw32 else ["DllCanUnloadNow,PRIVATE",
-                                              "DllGetClassObject,PRIVATE",
-                                              "DllRegisterServer,PRIVATE",
-                                              "DllUnregisterServer,PRIVATE",
-@@ -71,7 +78,7 @@ run_ctypes_dll = Interpreter("py2exe.run_ctypes_dll",
-                              target_desc = "shared_library",
-                              define_macros=macros,
-                              extra_compile_args=extra_compile_args,
--                             extra_link_args=extra_link_args + ["/DLL"],
-+                             extra_link_args=extra_link_args + ([] if isMingw32 else ["/DLL"]),
-                              )
- 
- run = Interpreter("py2exe.run",
-@@ -123,7 +130,7 @@ resource_dll = Interpreter("py2exe.resources",
-                            ["source/dll.c",
-                             "source/icon.rc"],
-                            target_desc = "shared_library",
--                           extra_link_args=["/DLL"],
-+                           extra_link_args=[] if isMingw32 else ["/DLL"],
-                            )
- 
- interpreters = [run, run_w, resource_dll,
-diff --git a/source/python-dynload.c b/source/python-dynload.c
-index 2a60b86..373bb62 100644
---- a/source/python-dynload.c
-+++ b/source/python-dynload.c
-@@ -31,7 +31,7 @@ static HMODULE hmod_pydll;
- 
- #define FUNC(res, name, args) \
-   static res(*proc)args; \
--  if (!proc) (FARPROC)proc = MyGetProcAddress(hmod_pydll, #name)
-+  if (!proc) proc = (res (*)args)MyGetProcAddress(hmod_pydll, #name)
- 
- #define DATA(type, name)				\
-   static type pflag; \
-@@ -158,7 +158,7 @@ void PyErr_Print(void)
-   proc();
- }
- 
--void Py_SetProgramName(wchar_t *name)
-+void Py_SetProgramName(const wchar_t *name)
- {
-   FUNC(void, Py_SetProgramName, (wchar_t *));
-   proc(name);
-diff --git a/source/run.c b/source/run.c
-index e1f630e..933ae77 100644
---- a/source/run.c
-+++ b/source/run.c
-@@ -54,7 +54,11 @@ extern int start(int argc, wchar_t **argv);
- /*
-   The main function for our exe.
- */
-+#if defined(__MINGW32__)
-+int main (int argc, wchar_t **argv)
-+#else
- int wmain (int argc, wchar_t **argv)
-+#endif
- {
- 	int result;
- 	result = init("console_exe");
-diff --git a/source/start.c b/source/start.c
-index e894ae6..6b61624 100644
---- a/source/start.c
-+++ b/source/start.c
-@@ -128,7 +128,7 @@ BOOL locate_script(HMODULE hmod)
- 		SystemError(GetLastError(), "Could not load script resource:");
- 		return FALSE;
- 	}
--	p_script_info = (struct scriptinfo *)pScript = LockResource(hgbl);
-+	p_script_info = (struct scriptinfo *)(pScript = LockResource(hgbl));
- 	if (!pScript)  {
- 		SystemError(GetLastError(), "Could not lock script resource:");
- 		return FALSE;
-diff --git a/setup.py b/setup.py
-index 342d194..1fe1e43 100644
---- a/setup.py
-+++ b/setup.py
-@@ -107,7 +107,7 @@ run_w = Interpreter("py2exe.run_w",
-                     libraries=["user32", "shell32"],
-                     define_macros=macros,
-                     extra_compile_args=extra_compile_args,
--                    extra_link_args=extra_link_args,
-+                    extra_link_args=extra_link_args + (["-Wl,--subsystem,windows"] if isMingw32 else []),
-                     )
- 
- # The py2exe.resources name is special handled in BuildInterpreters;
Index: docker/msys/pywin32.patch
===================================================================
--- docker/msys/pywin32.patch	(revision 920)
+++ docker/msys/pywin32.patch	(revision 920)
@@ -0,0 +1,2641 @@
+diff --git a/com/win32com/src/ErrorUtils.cpp b/com/win32com/src/ErrorUtils.cpp
+index 1186cd1..314aff8 100644
+--- a/com/win32com/src/ErrorUtils.cpp
++++ b/com/win32com/src/ErrorUtils.cpp
+@@ -1118,9 +1118,15 @@ LPCTSTR GetScodeRangeString(HRESULT hr)
+ 		HRESULT hrLast;
+ 		LPCTSTR lpszName;
+ 	};
++#if defined(__MINGW32__)
++	#define MAKE_RANGE_ENTRY(hrRange) \
++                { static_cast<HRESULT>(hrRange##_FIRST), static_cast<HRESULT>(hrRange##_LAST), \
++			_T(#hrRange) _T("_FIRST...") _T(#hrRange) _T("_LAST") }
++#else
+ 	#define MAKE_RANGE_ENTRY(hrRange) \
+ 		{ hrRange##_FIRST, hrRange##_LAST, \
+ 			_T(#hrRange) _T("_FIRST...") _T(#hrRange) _T("_LAST") }
++#endif
+ 
+ 	static const RANGE_ENTRY hrRangeTable[] =
+ 	{
+diff --git a/com/win32com/src/PyGatewayBase.cpp b/com/win32com/src/PyGatewayBase.cpp
+index fc091cb..2ed9acc 100644
+--- a/com/win32com/src/PyGatewayBase.cpp
++++ b/com/win32com/src/PyGatewayBase.cpp
+@@ -7,6 +7,10 @@
+ 
+ #include "PythonCOMServer.h"
+ 
++#if defined(__MINGW32__)
++#include <algorithm>
++#endif
++
+ // {25D29CD0-9B98-11d0-AE79-4CF1CF000000}
+ extern const GUID IID_IInternalUnwrapPythonObject = 
+ 	{ 0x25d29cd0, 0x9b98, 0x11d0, { 0xae, 0x79, 0x4c, 0xf1, 0xcf, 0x0, 0x0, 0x0 } };
+@@ -437,7 +441,11 @@ static HRESULT invoke_setup(
+ 		// make sure its not a special DISPID we don't understand.
+ 		if (params->rgdispidNamedArgs[i] < 0)
+ 			return DISP_E_PARAMNOTFOUND;
++#if defined(__MINGW32__)
++		numArgs = std::max(numArgs, (UINT)params->rgdispidNamedArgs[i]+1);
++#else
+ 		numArgs = max(numArgs, (UINT)params->rgdispidNamedArgs[i]+1);
++#endif
+ 	}
+ 
+ 	PyObject *argList = PyTuple_New(numArgs);
+@@ -658,7 +666,11 @@ static HRESULT invoke_finish(
+ 			ob = NULL;
+ 			firstByRef = 1;
+ 		}
++#if defined(__MINGW32__)
++		UINT max_args = std::min(cUserResult-firstByRef, pDispParams->cArgs);
++#else
+ 		UINT max_args = min(cUserResult-firstByRef, pDispParams->cArgs);
++#endif
+ 		UINT *offsets = (UINT *)_malloca(sizeof(UINT) * max_args);
+ 		// Get the offsets into our params of all BYREF args, in order.
+ 		fill_byref_offsets(pDispParams, offsets, max_args);
+diff --git a/com/win32com/src/PythonCOM.cpp b/com/win32com/src/PythonCOM.cpp
+index da00839..67983a4 100644
+--- a/com/win32com/src/PythonCOM.cpp
++++ b/com/win32com/src/PythonCOM.cpp
+@@ -342,11 +342,13 @@ static PyObject *pythoncom_CoInitializeSecurity(PyObject *self, PyObject *args)
+ 			pSD = (PSECURITY_DESCRIPTOR)&appid;
+ 			}
+ 		}
++#if !defined(__MINGW32__)
+ 	else if (dwCapabilities & EOAC_ACCESS_CONTROL){
+ 		if (!PyCom_InterfaceFromPyObject(obSD, IID_IAccessControl, (void **)&pIAC, FALSE))
+ 			return NULL;
+ 		pSD = (PSECURITY_DESCRIPTOR)pIAC;
+ 		}
++#endif
+ 	else{
+ 		if (!PyWinObject_AsSECURITY_DESCRIPTOR(obSD, &pSD, /*BOOL bNoneOK = */TRUE))
+ 			return NULL;
+diff --git a/com/win32com/src/PythonCOM.def b/com/win32com/src/PythonCOM.def
+index 58d030f..6d2a54b 100644
+--- a/com/win32com/src/PythonCOM.def
++++ b/com/win32com/src/PythonCOM.def
+@@ -1,15 +1,15 @@
+ EXPORTS
+-	DllCanUnloadNow     @1 PRIVATE
+-	DllGetClassObject   @2 PRIVATE
++	DllCanUnloadNow
++	DllGetClassObject
+ 
+ 	; Some exports for clients who may "LoadLibrary"...
+-	PyCom_VariantFromPyObject
+-	PyCom_PyObjectFromVariant
+-	PyCom_InterfaceFromPyObject
+-	PyCom_PyObjectFromIUnknown
+-	PyCom_MakeOlePythonCall
++	_PyCom_VariantFromPyObject
++	_PyCom_PyObjectFromVariant
++	_PyCom_InterfaceFromPyObject
++	_PyCom_PyObjectFromIUnknown
++	_PyCom_MakeOlePythonCall
+ 
+-	PyCom_CoInitializeEx
+-	PyCom_CoInitialize
+-	PyCom_CoUninitialize
++	_PyCom_CoInitializeEx
++	_PyCom_CoInitialize
++	_PyCom_CoUninitialize
+ 
+diff --git a/com/win32com/src/Register.cpp b/com/win32com/src/Register.cpp
+index 0b24ee2..d259aff 100644
+--- a/com/win32com/src/Register.cpp
++++ b/com/win32com/src/Register.cpp
+@@ -322,7 +322,9 @@ static const PyCom_InterfaceSupportInfo g_interfaceSupportData[] =
+ 	PYCOM_INTERFACE_FULL	   ( CancelMethodCalls),
+ 	// No wrapper for IAccessControl yet, but you can still get the system implementation
+ 	//  by calling pythoncom.CoCreateInstance with IID_IUnknown as the returned interface
++#if !defined(__MINGW32__)
+ 	PYCOM_INTERFACE_CLSID_ONLY (DCOMAccessControl),
++#endif
+ 
+ 	// NULL, Unknown and dispatch special cases.
+ 	{ &IID_NULL, "Null", "IID_NULL", NULL, NULL},
+diff --git a/com/win32com/src/dllmain.cpp b/com/win32com/src/dllmain.cpp
+index fb81ddb..abf074c 100644
+--- a/com/win32com/src/dllmain.cpp
++++ b/com/win32com/src/dllmain.cpp
+@@ -175,6 +175,9 @@ typedef HRESULT (WINAPI *PFNCoInitializeEx)(LPVOID pvReserved, DWORD dwCoInit);
+ // the Init for Term function explicitely, and the framework will detect
+ // it no longer needs doing.
+ // XXX - Needs more thought about threading implications.
++#if defined(__MINGW32__)
++extern "C"
++#endif
+ HRESULT PyCom_CoInitializeEx(LPVOID reserved, DWORD dwInit)
+ {
+ 	// Must be thread-safe, although doesnt need the Python lock.
+diff --git a/com/win32com/src/include/PythonCOM.h b/com/win32com/src/include/PythonCOM.h
+index 9e422e4..f3b1063 100644
+--- a/com/win32com/src/include/PythonCOM.h
++++ b/com/win32com/src/include/PythonCOM.h
+@@ -111,10 +111,8 @@
+ #ifdef __MINGW32__
+ // Special Mingw32 considerations.
+ #define NO_PYCOM_IDISPATCHEX
+-#define NO_PYCOM_IPROVIDECLASSINFO
+ #define NO_PYCOM_ISERVICEPROVIDER
+ #define NO_PYCOM_ENUMSTATPROPSTG
+-#define NO_PYCOM_IPROPERTYSTORAGE
+ #define __try try
+ #define __except catch
+ #include <olectl.h>
+@@ -305,6 +303,9 @@ PYCOM_EXPORT PyObject *PyObject_FromOLEMENUGROUPWIDTHS(const OLEMENUGROUPWIDTHS
+ 
+ /* Functions for Initializing COM, and also letting the core know about it!
+ */
++#if defined(__MINGW32__)
++extern "C"
++#endif
+ PYCOM_EXPORT HRESULT PyCom_CoInitializeEx(LPVOID reserved, DWORD dwInit);
+ PYCOM_EXPORT HRESULT PyCom_CoInitialize(LPVOID reserved);
+ PYCOM_EXPORT void PyCom_CoUninitialize();
+diff --git a/com/win32com/src/initguid.cpp b/com/win32com/src/initguid.cpp
+new file mode 100644
+index 0000000..33d5923
+--- /dev/null
++++ b/com/win32com/src/initguid.cpp
+@@ -0,0 +1,7 @@
++#define INITGUID
++#undef _OBJIDLBASE_
++#define CINTERFACE
++#define USE_COM_CONTEXT_DEF
++#include <objidl.h>
++#include <ksguid.h>
++#include <ks.h>
+diff --git a/com/win32comext/axcontrol/src/PyIOleCommandTarget.cpp b/com/win32comext/axcontrol/src/PyIOleCommandTarget.cpp
+index 61bd706..e7908e9 100644
+--- a/com/win32comext/axcontrol/src/PyIOleCommandTarget.cpp
++++ b/com/win32comext/axcontrol/src/PyIOleCommandTarget.cpp
+@@ -4,6 +4,10 @@
+ #include "axcontrol_pch.h"
+ #include "PyIOleCommandTarget.h"
+ 
++#if defined(__MINGW32__)
++#include <algorithm>
++#endif
++
+ static BOOL FillOLECMDsWithSequence(OLECMD *pCmds, UINT ncmds, PyObject *obCmds)
+ {
+ 	for (UINT i=0;i<ncmds;i++) {
+@@ -211,7 +215,11 @@ STDMETHODIMP PyGOleCommandTarget::QueryStatus(
+ 			ok = PyWinObject_AsAutoFreeBstr(obText, &tempString);
+ 			if (ok) {
+ 				UINT strLen = SysStringLen(tempString);
++#if defined(__MINGW32__)
++				UINT nwrite = std::min((ULONG)strLen, pCmdText->cwBuf);
++#else
+ 				UINT nwrite = min(strLen, pCmdText->cwBuf);
++#endif
+ 				wcsncpy(pCmdText->rgwz, (WCHAR *)(BSTR)tempString,
+ 					nwrite);
+ 				pCmdText->cwActual = nwrite;
+diff --git a/com/win32comext/axcontrol/src/initguid.cpp b/com/win32comext/axcontrol/src/initguid.cpp
+new file mode 100644
+index 0000000..329e211
+--- /dev/null
++++ b/com/win32comext/axcontrol/src/initguid.cpp
+@@ -0,0 +1,8 @@
++#define INITGUID
++#undef _OBJIDLBASE_
++#define CINTERFACE
++#define USE_COM_CONTEXT_DEF
++#include <objidl.h>
++#include <ksguid.h>
++#include <ks.h>
++#include <docobj.h>
+diff --git a/com/win32comext/axscript/src/initguid.cpp b/com/win32comext/axscript/src/initguid.cpp
+new file mode 100644
+index 0000000..ba6baa3
+--- /dev/null
++++ b/com/win32comext/axscript/src/initguid.cpp
+@@ -0,0 +1,8 @@
++#define INITGUID
++#undef _OBJIDLBASE_
++#define CINTERFACE
++#define USE_COM_CONTEXT_DEF
++#include <objidl.h>
++#include <ksguid.h>
++#include <ks.h>
++#include <objsafe.h>
+diff --git a/com/win32comext/internet/src/PyIInternetProtocol.cpp b/com/win32comext/internet/src/PyIInternetProtocol.cpp
+index 43c25a8..b910c85 100644
+--- a/com/win32comext/internet/src/PyIInternetProtocol.cpp
++++ b/com/win32comext/internet/src/PyIInternetProtocol.cpp
+@@ -5,6 +5,10 @@
+ #include "PyIInternetProtocolRoot.h"
+ #include "PyIInternetProtocol.h"
+ 
++#if defined(__MINGW32__)
++#include <algorithm>
++#endif
++
+ // @doc - This file contains autoduck documentation
+ // ---------------------------------------------------
+ //
+@@ -181,7 +185,11 @@ STDMETHODIMP PyGInternetProtocol::Read(
+ 		hr = PyCom_HandlePythonFailureToCOM();
+ 	} else {
+ 		char *buf = PyString_AsString(result);
++#if defined(__MINGW32__)
++		*pcbRead = std::min(cb, (ULONG)PyString_Size(result));
++#else
+ 		*pcbRead = min(cb, (ULONG)PyString_Size(result));
++#endif
+ 		memcpy( pv, buf, *pcbRead);
+ 	}
+ 	return hr;
+diff --git a/com/win32comext/internet/src/PyIInternetProtocolInfo.cpp b/com/win32comext/internet/src/PyIInternetProtocolInfo.cpp
+index c00e43e..ef894ca 100644
+--- a/com/win32comext/internet/src/PyIInternetProtocolInfo.cpp
++++ b/com/win32comext/internet/src/PyIInternetProtocolInfo.cpp
+@@ -4,6 +4,10 @@
+ #include "internet_pch.h"
+ #include "PyIInternetProtocolInfo.h"
+ 
++#if defined(__MINGW32__)
++#include <algorithm>
++#endif
++
+ // @doc - This file contains autoduck documentation
+ // ---------------------------------------------------
+ //
+@@ -226,7 +230,11 @@ STDMETHODIMP PyGInternetProtocolInfo::ParseUrl(
+ 	if (!PyWinObject_AsBstr(result, &bstrTemp, FALSE, pcchResult)) bPythonIsHappy = FALSE;
+ 	if (!bPythonIsHappy) return PyCom_HandlePythonFailureToCOM(/*pexcepinfo*/);
+ 	++(*pcchResult); // Null terminator
++#if defined(__MINGW32__)
++	*pcchResult = std::min(*pcchResult, cchResult);
++#else
+ 	*pcchResult = min(*pcchResult, cchResult);
++#endif
+ 	memcpy(pwzResult, bstrTemp, *pcchResult * sizeof(WCHAR));
+ 	SysFreeString(bstrTemp);
+ 	Py_DECREF(result);
+@@ -258,7 +266,11 @@ STDMETHODIMP PyGInternetProtocolInfo::CombineUrl(
+ 	if (!PyWinObject_AsBstr(result, &bstrTemp, FALSE, pcchResult)) bPythonIsHappy = FALSE;
+ 	if (!bPythonIsHappy) hr = PyCom_HandlePythonFailureToCOM(/*pexcepinfo*/);
+ 	++(*pcchResult); // Null terminator
++#if defined(__MINGW32__)
++	*pcchResult = std::min(*pcchResult, cchResult);
++#else
+ 	*pcchResult = min(*pcchResult, cchResult);
++#endif
+ 	memcpy(pwzResult, bstrTemp, *pcchResult * sizeof(WCHAR));
+ 	SysFreeString(bstrTemp);
+ 	Py_DECREF(result);
+@@ -312,7 +324,11 @@ STDMETHODIMP PyGInternetProtocolInfo::QueryInfo(
+ 			return PyCom_HandlePythonFailureToCOM();
+ 		}
+ 	} else {
++#if defined(__MINGW32__)
++		*pcbBuf = std::min(cbBuffer, (ULONG)PyString_Size(result));
++#else
+ 		*pcbBuf = min(cbBuffer, (ULONG)PyString_Size(result));
++#endif
+ 		memcpy(pBuffer, PyString_AsString(result), *pcbBuf);
+ 	}
+ 	Py_DECREF(result);
+diff --git a/com/win32comext/internet/src/PyIInternetSecurityManager.cpp b/com/win32comext/internet/src/PyIInternetSecurityManager.cpp
+index 81439fc..a4cb106 100644
+--- a/com/win32comext/internet/src/PyIInternetSecurityManager.cpp
++++ b/com/win32comext/internet/src/PyIInternetSecurityManager.cpp
+@@ -4,6 +4,10 @@
+ #include "internet_pch.h"
+ #include "PyIInternetSecurityManager.h"
+ 
++#if defined(__MINGW32__)
++#include <algorithm>
++#endif
++
+ // @doc - This file contains autoduck documentation
+ // ---------------------------------------------------
+ //
+@@ -338,7 +342,11 @@ STDMETHODIMP PyGInternetSecurityManager::GetSecurityId(
+ 		Py_DECREF(result);
+ 		return MAKE_PYCOM_GATEWAY_FAILURE_CODE("GetSecurityId");
+ 	}
++#if defined(__MINGW32__)
++	*pcbSecurityId = std::min(buf_len, *pcbSecurityId);
++#else
+ 	*pcbSecurityId = min(buf_len, *pcbSecurityId);
++#endif
+ 	memcpy(pbSecurityId, buf, *pcbSecurityId);
+ 	Py_DECREF(result);
+ 	return hr;
+diff --git a/com/win32comext/internet/src/initguid.cpp b/com/win32comext/internet/src/initguid.cpp
+new file mode 100644
+index 0000000..1003585
+--- /dev/null
++++ b/com/win32comext/internet/src/initguid.cpp
+@@ -0,0 +1,9 @@
++#define INITGUID
++#undef _OBJIDLBASE_
++#define CINTERFACE
++#define USE_COM_CONTEXT_DEF
++#include <objidl.h>
++#include <ksguid.h>
++#include <ks.h>
++#include <urlmon.h>
++#include <mshtmhst.h>
+diff --git a/com/win32comext/propsys/src/PyPROPVARIANT.cpp b/com/win32comext/propsys/src/PyPROPVARIANT.cpp
+index b330129..694703f 100644
+--- a/com/win32comext/propsys/src/PyPROPVARIANT.cpp
++++ b/com/win32comext/propsys/src/PyPROPVARIANT.cpp
+@@ -3,7 +3,13 @@
+ 
+ #include "PythonCOM.h"
+ #include "PyPROPVARIANT.h"
++#if defined(__MINGW32__)
++extern "C" {
++#endif
+ #include "propvarutil.h"
++#if defined(__MINGW32__)
++}
++#endif
+ #include "float.h"
+ 
+ // @doc - This file contains autoduck documentation
+diff --git a/com/win32comext/propsys/src/propsys.cpp b/com/win32comext/propsys/src/propsys.cpp
+index ef0a2f4..69ff21f 100644
+--- a/com/win32comext/propsys/src/propsys.cpp
++++ b/com/win32comext/propsys/src/propsys.cpp
+@@ -279,6 +279,7 @@ static PyObject *PyPSGetItemPropertyHandler(PyObject *self, PyObject *args)
+ 	return PyCom_PyObjectFromIUnknown((IUnknown *)propertystore, riid, FALSE);
+ }
+ 
++#if !defined(__MINGW32__)
+ // @pymethod bytes|propsys|StgSerializePropVariant|Serializes a <o PyPROPVARIANT>
+ static PyObject *PyStgSerializePropVariant(PyObject *self, PyObject *args)
+ {
+@@ -319,6 +320,7 @@ static PyObject *PyStgDeserializePropVariant(PyObject *self, PyObject *args)
+ 		return PyCom_BuildPyException(hr);
+ 	return PyWinObject_FromPROPVARIANT(&pv);
+ };
++#endif
+ 
+ // @pymethod <o PyIPropertyStore>|propsys|PSCreateMemoryPropertyStore|Creates a temporary property store that is not connected to any backing storage
+ // @comm May also be used to create <o PyINamedPropertyStore>, <o PyIPropertyStoreCache>, <o PyIPersistStream>, or <o PyIPropertyBag>
+@@ -566,8 +568,10 @@ static struct PyMethodDef propsys_methods[]=
+ 	{ "PSRegisterPropertySchema", PyPSRegisterPropertySchema, 1 }, // @pymeth PSRegisterPropertySchema|Registers a group of properties described in a schema file
+ 	{ "PSUnregisterPropertySchema", PyPSUnregisterPropertySchema, 1 }, // @pymeth PSUnregisterPropertySchema|Removes a property schema definition
+ 	{ "SHGetPropertyStoreFromParsingName", PySHGetPropertyStoreFromParsingName, 1 }, // @pymeth SHGetPropertyStoreFromParsingName|Retrieves the property store for an item by path
++#if !defined(__MINGW32__)
+ 	{ "StgSerializePropVariant", PyStgSerializePropVariant, 1 }, // @pymeth StgSerializePropVariant|Serializes a <o PyPROPVARIANT>
+ 	{ "StgDeserializePropVariant", PyStgDeserializePropVariant, 1 }, // @pymeth StgDeserializePropVariant|Creates a <o PyPROPVARIANT> from a serialized buffer
++#endif
+ 	{ "PSCreateMemoryPropertyStore", PyPSCreateMemoryPropertyStore, 1 }, // @pymeth PSCreateMemoryPropertyStore|Creates a temporary property store that is not connected to any backing storage
+ 	{ "PSCreatePropertyStoreFromPropertySetStorage", PyPSCreatePropertyStoreFromPropertySetStorage, 1 }, // @pymeth PSCreatePropertyStoreFromPropertySetStorage|Wraps a <o PyIPropertySetStorage> interface in a <o PyIPropertyStore> object
+ 	{ "PSLookupPropertyHandlerCLSID", PyPSLookupPropertyHandlerCLSID, 1 }, // @pymeth PSLookupPropertyHandlerCLSID|Returns the GUID of the property handler for a file
+@@ -583,7 +587,7 @@ static struct PyMethodDef propsys_methods[]=
+ 	// MSDN says CLSID_PropertyChangeArray can be used to create IPropertyChangeArray, but
+ 	// I get "Class not registered".  Plus, it doesn't appear in any headers, although
+ 	// it's contained in uuid.lib.
+-#ifndef CLSID_PropertyChangeArray
++#if !defined(CLSID_PropertyChangeArray) && !defined(__MINGW32__)
+ 	EXTERN_C const CLSID CLSID_PropertyChangeArray;
+ #endif
+ 
+@@ -606,7 +610,9 @@ static const PyCom_InterfaceSupportInfo g_interfaceSupportData[] =
+ 	PYCOM_INTERFACE_CLIENT_ONLY (ObjectWithPropertyKey),
+ 	PYCOM_INTERFACE_CLIENT_ONLY (PropertyChange),
+ 	PYCOM_INTERFACE_CLIENT_ONLY (PropertyChangeArray),
++#if !defined(__MINGW32__)
+ 	PYCOM_INTERFACE_CLSID_ONLY (PropertyChangeArray),
++#endif
+ };
+ 
+ /* Module initialisation */
+diff --git a/com/win32comext/shell/src/PyICategoryProvider.cpp b/com/win32comext/shell/src/PyICategoryProvider.cpp
+index e2f2ea8..0ecf0cf 100644
+--- a/com/win32comext/shell/src/PyICategoryProvider.cpp
++++ b/com/win32comext/shell/src/PyICategoryProvider.cpp
+@@ -9,6 +9,10 @@
+ //
+ // Interface Implementation
+ 
++#if defined(__MINGW32__)
++__CRT_UUID_DECL(int, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
++#endif
++
+ PyICategoryProvider::PyICategoryProvider(IUnknown *pdisp):
+ 	PyIUnknown(pdisp)
+ {
+diff --git a/com/win32comext/shell/src/initguid.cpp b/com/win32comext/shell/src/initguid.cpp
+new file mode 100644
+index 0000000..8da5c87
+--- /dev/null
++++ b/com/win32comext/shell/src/initguid.cpp
+@@ -0,0 +1,11 @@
++#define INITGUID
++#undef _OBJIDLBASE_
++#define CINTERFACE
++#define USE_COM_CONTEXT_DEF
++#include <objidl.h>
++#include <ksguid.h>
++#include <ks.h>
++#include <shlguid.h>
++#include <shobjidl.h>
++#include <emptyvc.h>
++#include <_mingw.h>
+diff --git a/com/win32comext/shell/src/shell.cpp b/com/win32comext/shell/src/shell.cpp
+index 8b6e78c..f19a021 100644
+--- a/com/win32comext/shell/src/shell.cpp
++++ b/com/win32comext/shell/src/shell.cpp
+@@ -29,8 +29,10 @@ generates Windows .hlp files.
+ #include "PyIShellExtInit.h"
+ #include "PyIShellFolder.h"
+ #include "PyIShellFolder2.h"
++#if !defined(__MINGW32__)
+ #include "PyIEmptyVolumeCache.h"
+ #include "PyIEmptyVolumeCacheCallBack.h"
++#endif
+ #include "PyIEnumExplorerCommand.h"
+ #include "PyIEnumIDList.h"
+ #include "PyICopyHook.h"
+@@ -3606,12 +3608,16 @@ static const PyCom_InterfaceSupportInfo g_interfaceSupportData[] =
+ 	PYCOM_INTERFACE_FULL(ColumnProvider),
+ 	PYCOM_INTERFACE_CLIENT_ONLY(DefaultExtractIconInit),
+ 	PYCOM_INTERFACE_FULL(DropTargetHelper),
++#if !defined(__MINGW32__)
+ 	PYCOM_INTERFACE_CLIENT_ONLY(EmptyVolumeCacheCallBack),
++#endif
+ 	PYCOM_INTERFACE_CLIENT_ONLY(QueryAssociations),
+ 	PYCOM_INTERFACE_SERVER_ONLY(DeskBand),
+ 	PYCOM_INTERFACE_SERVER_ONLY(DockingWindow),
++#if !defined(__MINGW32__)
+ 	PYCOM_INTERFACE_SERVER_ONLY(EmptyVolumeCache),
+ 	PYCOM_INTERFACE_SERVER_ONLY(EmptyVolumeCache2),
++#endif
+ 	PYCOM_INTERFACE_CLIENT_ONLY(ExplorerBrowser),
+ 	PYCOM_INTERFACE_FULL(ExplorerBrowserEvents),
+ 	PYCOM_INTERFACE_FULL(ExplorerCommand),
+@@ -3850,12 +3856,16 @@ PYWIN_MODULE_INIT_FUNC(shell)
+ 	ADD_IID(FMTID_Briefcase);
+ 	ADD_IID(FMTID_Misc);
+ 	ADD_IID(FMTID_WebView);
++#if !defined(__MINGW32__)
+ 	ADD_IID(FMTID_AudioSummaryInformation);
++#endif
+ 	ADD_IID(FMTID_Volume);
+ 	ADD_IID(FMTID_Query);
++#if !defined(__MINGW32__)
+ 	ADD_IID(FMTID_SummaryInformation);
+ 	ADD_IID(FMTID_MediaFileSummaryInformation);
+ 	ADD_IID(FMTID_ImageSummaryInformation);
++#endif
+ 	ADD_IID(IID_CDefView);
+ 
+ 	ADD_IID(EP_NavPane);
+diff --git a/com/win32comext/taskscheduler/src/initguid.cpp b/com/win32comext/taskscheduler/src/initguid.cpp
+new file mode 100644
+index 0000000..d588502
+--- /dev/null
++++ b/com/win32comext/taskscheduler/src/initguid.cpp
+@@ -0,0 +1,8 @@
++#define INITGUID
++#undef _OBJIDLBASE_
++#define CINTERFACE
++#define USE_COM_CONTEXT_DEF
++#include <objidl.h>
++#include <ksguid.h>
++#include <ks.h>
++#include <mstask.h>
+diff --git a/isapi/src/Utils.cpp b/isapi/src/Utils.cpp
+index 8f278f2..b8976ae 100644
+--- a/isapi/src/Utils.cpp
++++ b/isapi/src/Utils.cpp
+@@ -127,7 +127,11 @@ static void CheckRegisterEventSourceFile()
+ 		return;
+ 
+ 	GetModuleFileNameW(g_hInstance, mod_name,
++#if defined(__MINGW32__)
++			  sizeof(mod_name)/sizeof(WCHAR));
++#else
+ 			  sizeof mod_name/sizeof WCHAR);
++#endif
+ 	if (!mod_name[0]) {
+ 		OutputDebugString(_T("GetModuleFileNameW failed!"));
+ 		return;
+@@ -160,6 +164,9 @@ static void CheckRegisterEventSourceFile()
+ }
+ 
+ // Write stuff to the event log.
++#if defined(__MINGW32__)
++extern "C"
++#endif
+ BOOL WriteEventLogMessage(WORD eventType, DWORD eventID, WORD num_inserts,
+                           const char **inserts)
+ {
+diff --git a/isapi/src/Utils.h b/isapi/src/Utils.h
+index 3779ca9..f076826 100644
+--- a/isapi/src/Utils.h
++++ b/isapi/src/Utils.h
+@@ -58,6 +58,9 @@ char *HTMLErrorResp(const char *msg);
+ TCHAR *GetModulePath(void);
+ 
+ // Write entry to the event log
++#if defined(__MINGW32__)
++extern "C"
++#endif
+ BOOL WriteEventLogMessage(WORD eventType, DWORD eventID, WORD num_inserts,
+                           const char **inserts);
+ 
+diff --git a/isapi/src/pyISAPI.cpp b/isapi/src/pyISAPI.cpp
+index 439d3ca..2c94610 100644
+--- a/isapi/src/pyISAPI.cpp
++++ b/isapi/src/pyISAPI.cpp
+@@ -52,6 +52,9 @@ char g_CallbackModuleName[_MAX_PATH + _MAX_FNAME] = "";
+ #define TRACE(x) OutputDebugString(_T(x))
+ 
+ // This is an entry point for py2exe.
++#if defined(__MINGW32__)
++extern "C"
++#endif
+ void WINAPI PyISAPISetOptions(const char *modname, BOOL is_frozen)
+ {
+ 	strncpy(g_CallbackModuleName, modname,
+diff --git a/setup.py b/setup.py
+index 7c35d90..5872968 100644
+--- a/setup.py
++++ b/setup.py
+@@ -72,6 +72,8 @@ import shutil
+ 
+ is_py3k = sys.version_info > (3,) # get this out of the way early on...
+ 
++build_mingw32=True
++
+ try:
+     import winreg # py3k
+ except ImportError:
+@@ -140,6 +142,10 @@ dll_base_address = 0x1e200000
+ def find_platform_sdk_dir():
+     # The user might have their current environment setup for the
+     # SDK, in which case "MSSDK_INCLUDE" and "MSSDK_LIB" vars must be set.
++    if build_mingw32:
++        return { "include": ["c:/msys64/mingw32/include", "c:/msys64/mingw32/i686-w64-mingw32/include"], 
++	         "lib": ["c:/msys64/mingw32/lib", "c:/msys64//mingw32/i686-w64-mingw32/lib"] }
++
+     if "MSSDK_INCLUDE" in os.environ and "MSSDK_LIB" in os.environ:
+         print("Using SDK as specified in the environment")
+         return {
+@@ -173,9 +179,10 @@ def find_platform_sdk_dir():
+ # to prevent the extension from loading.  For more details, see
+ # http://bugs.python.org/issue7833 (which has landed for Python 2.7 and on 3.2
+ # and later, which are all we care about currently)
+-from distutils.msvc9compiler import MSVCCompiler
+-MSVCCompiler._orig_spawn = MSVCCompiler.spawn
+-MSVCCompiler._orig_link = MSVCCompiler.link
++if not build_mingw32:
++    from distutils.msvc9compiler import MSVCCompiler
++    MSVCCompiler._orig_spawn = MSVCCompiler.spawn
++    MSVCCompiler._orig_link = MSVCCompiler.link
+ 
+ # We need to override this method for versions where issue7833 *has* landed
+ # (ie, 2.7 and 3.2+)
+@@ -195,7 +202,8 @@ def manifest_get_embed_info(self, target_desc, ld_args):
+ 
+ # always monkeypatch it in even though it will only be called in 2.7
+ # and 3.2+.
+-MSVCCompiler.manifest_get_embed_info = manifest_get_embed_info
++if not build_mingw32:
++    MSVCCompiler.manifest_get_embed_info = manifest_get_embed_info
+ 
+ def monkeypatched_spawn(self, cmd):
+     is_link = cmd[0].endswith("link.exe") or cmd[0].endswith('"link.exe"')
+@@ -239,8 +247,9 @@ def monkeypatched_link(self, target_desc, objects, output_filename, *args, **kw)
+         return self._orig_link(target_desc, objects, output_filename, *args, **kw)
+     finally:
+         delattr(self, '_want_assembly_kept')
+-MSVCCompiler.spawn = monkeypatched_spawn
+-MSVCCompiler.link = monkeypatched_link
++if not build_mingw32:
++    MSVCCompiler.spawn = monkeypatched_spawn
++    MSVCCompiler.link = monkeypatched_link
+ 
+ 
+ sdk_info = find_platform_sdk_dir()
+@@ -449,6 +458,18 @@ class WinExt (Extension):
+                 # Unicode, Windows executables seem to need this magic:
+                 if "/SUBSYSTEM:WINDOWS" in self.extra_link_args:
+                     self.extra_link_args.append("/ENTRY:wWinMainCRTStartup")
++        else:
++            self.extra_compile_args.append("-fpermissive")
++            unicode_mode = self.unicode_mode
++            if unicode_mode is None:
++                unicode_mode = is_py3k
++            if unicode_mode:
++                self.extra_compile_args.append("-DUNICODE")
++                self.extra_compile_args.append("-D_UNICODE")
++                self.extra_compile_args.append("-DWINNT")
++                # Unicode, Windows executables seem to need this magic:
++                #if "/SUBSYSTEM:WINDOWS" in self.extra_link_args:
++                #    self.extra_link_args.append("/ENTRY:wWinMainCRTStartup")
+ 
+ class WinExt_pythonwin(WinExt):
+     def __init__ (self, name, **kw):
+@@ -641,7 +662,7 @@ class my_build_ext(build_ext):
+         # The pywintypes library is created in the build_temp
+         # directory, so we need to add this to library_dirs
+         self.library_dirs.append(self.build_temp)
+-        self.mingw32 = (self.compiler == "mingw32")
++        self.mingw32 = build_mingw32
+         if self.mingw32:
+             self.libraries.append("stdc++")
+ 
+@@ -698,7 +719,8 @@ class my_build_ext(build_ext):
+             self.compiler.add_include_dir(extra)
+         # and again for lib dirs.
+         for extra in sdk_info["lib"]:
+-            extra = os.path.join(extra, 'x64' if is_64bit else 'x86')
++            if not build_mingw32:
++                extra = os.path.join(extra, 'x64' if is_64bit else 'x86')
+             assert os.path.isdir(extra), extra
+             assert extra not in self.library_dirs # see above
+             assert os.path.isdir(extra), "%s doesn't exist!" % (extra,)
+@@ -714,7 +736,7 @@ class my_build_ext(build_ext):
+         # includes interfaces for 64-bit builds.
+         if self.plat_name == 'win-amd64' and ext.name == 'exchdapi':
+             return "No 64-bit library for utility functions available."
+-        if get_build_version() >=14:
++        if not build_mingw32 and get_build_version() >=14:
+             if ext.name == 'exchange':
+                 ext.libraries.append('legacy_stdio_definitions')
+             elif ext.name == 'exchdapi':
+@@ -758,7 +780,8 @@ class my_build_ext(build_ext):
+ 
+         # We update the .libraries list with the resolved library name.
+         # This is really only so "_d" works.
+-        ext.libraries = patched_libs
++        if not build_mingw32:
++            ext.libraries = patched_libs
+         return None # no reason - it can be built!
+ 
+     def _build_scintilla(self):
+@@ -972,11 +995,16 @@ class my_build_ext(build_ext):
+         if sys.version_info > (2, 7) and sys.version_info < (3, 3):
+             # only stuff built with msvc9 needs this loader.
+             self._build_pycom_loader()
+-        self._build_scintilla()
++        if not build_mingw32:
++            self._build_scintilla()
+         # Copy cpp lib files needed to create Python COM extensions
+-        clib_files = (['win32', 'pywintypes%s.lib'],
+-                      ['win32com', 'pythoncom%s.lib'],
+-                      ['win32com', 'axscript%s.lib'])
++        if build_mingw32:
++            clib_files = (['win32', 'libpywintypes%s.a'],
++                          ['win32com', 'libpythoncom%s.a'])
++        else:
++            clib_files = (['win32', 'pywintypes%s.lib'],
++                          ['win32com', 'pythoncom%s.lib'],
++                          ['win32com', 'axscript%s.lib'])
+         for clib_file in clib_files:
+             target_dir = os.path.join(self.build_lib, clib_file[0], "libs")
+             if not os.path.exists(target_dir):
+@@ -988,6 +1016,8 @@ class my_build_ext(build_ext):
+             self.copy_file(os.path.join(self.build_temp, fname),
+                            target_dir
+                            )
++        if build_mingw32:
++            return
+         # The MFC DLLs.
+         target_dir = os.path.join(self.build_lib, "pythonwin")
+ 
+@@ -1081,9 +1111,13 @@ class my_build_ext(build_ext):
+         # this, distutils gets confused, as they both try and use the same
+         # .obj.
+         output_dir = os.path.join(self.build_temp, ext.name)
++        if build_mingw32:
++            include_dirs = [output_dir, os.path.join(output_dir, "win32", "src")] + ext.include_dirs
++        else:
++            include_dirs = ext.include_dirs
+         kw = {'output_dir': output_dir,
+               'macros': macros,
+-              'include_dirs': ext.include_dirs,
++              'include_dirs': include_dirs,
+               'debug': self.debug,
+               'extra_postargs': extra_args,
+               'depends': ext.depends,
+@@ -1115,6 +1149,7 @@ class my_build_ext(build_ext):
+                'extra_postargs': extra_args,
+                'debug': self.debug,
+                'build_temp': self.build_temp,
++               'extra_preargs': []
+         }
+ 
+         # Detect target language, if not provided
+@@ -1162,22 +1197,37 @@ class my_build_ext(build_ext):
+         old_build_temp = self.build_temp
+         want_static_crt = sys.version_info > (2,6) and ext.name in static_crt_modules
+         if want_static_crt:
+-            self.compiler.compile_options.remove('/MD')
+-            self.compiler.compile_options.append('/MT')
+-            self.compiler.compile_options_debug.remove('/MDd')
+-            self.compiler.compile_options_debug.append('/MTd')
++            if not build_mingw32:
++                self.compiler.compile_options.remove('/MD')
++                self.compiler.compile_options.append('/MT')
++                self.compiler.compile_options_debug.remove('/MDd')
++                self.compiler.compile_options_debug.append('/MTd')
+ 
+         try:
++            if build_mingw32:
++                incs = set()
++                for source in ext.sources:
++                    output_dir = os.path.join(self.build_temp, os.path.dirname(source))
++                    if output_dir not in incs:
++                        ext.include_dirs.append(output_dir)
++                        incs.add(output_dir)
+             build_ext.build_extension(self, ext)
+             # XXX This has to be changed for mingw32
+             # Get the .lib files we need.  This is limited to pywintypes,
+             # pythoncom and win32ui - but the first 2 have special names
+-            extra = self.debug and "_d.lib" or ".lib"
++            if build_mingw32:
++                extra = self.debug and "_d.a" or ".a"
++            else:
++                extra = self.debug and "_d.lib" or ".lib"
+             if ext.name in ("pywintypes", "pythoncom"):
+                 # The import libraries are created as PyWinTypes23.lib, but
+                 # are expected to be pywintypes.lib.
+-                name1 = "%s%d%d%s" % (ext.name, sys.version_info[0], sys.version_info[1], extra)
+-                name2 = "%s%s" % (ext.name, extra)
++                if build_mingw32:
++                    name1 = "lib%s%d%d%s" % (ext.name, sys.version_info[0], sys.version_info[1], extra)
++                    name2 = "lib%s%s" % (ext.name, extra)
++                else:
++                    name1 = "%s%d%d%s" % (ext.name, sys.version_info[0], sys.version_info[1], extra)
++                    name2 = "%s%s" % (ext.name, extra)
+             elif ext.name in ("win32ui",):
+                 name1 = name2 = ext.name + extra
+             else:
+@@ -1199,10 +1249,11 @@ class my_build_ext(build_ext):
+         finally:
+             self.build_temp = old_build_temp
+             if want_static_crt:
+-                self.compiler.compile_options.remove('/MT')
+-                self.compiler.compile_options.append('/MD')
+-                self.compiler.compile_options_debug.remove('/MTd')
+-                self.compiler.compile_options_debug.append('/MDd')
++                if not build_mingw32:
++                    self.compiler.compile_options.remove('/MT')
++                    self.compiler.compile_options.append('/MD')
++                    self.compiler.compile_options_debug.remove('/MTd')
++                    self.compiler.compile_options_debug.append('/MDd')
+ 
+     def get_ext_filename(self, name):
+         # The pywintypes and pythoncom extensions have special names
+@@ -1298,6 +1349,8 @@ class my_build_ext(build_ext):
+         for source in swig_sources:
+             swig_cmd = [swig, "-python", "-c++"]
+             swig_cmd.append("-dnone",) # we never use the .doc files.
++            if not build_mingw32:
++                swig_cmd.append("-I" + os.path.abspath("swig/swig_lib/python"))
+             swig_cmd.extend(self.current_extension.extra_swig_commands)
+             if not is_py3k:
+                 swig_cmd.append("-DSWIG_PY2K")
+@@ -1368,7 +1421,10 @@ class my_install(install):
+         if not self.dry_run and not self.root:
+             # We must run the script we just installed into Scripts, as it
+             # may have had 2to3 run over it.
+-            filename = os.path.join(self.prefix, "Scripts", "pywin32_postinstall.py")
++            if build_mingw32:
++                filename = os.path.join(self.prefix, "bin", "pywin32_postinstall.py")
++            else:
++                filename = os.path.join(self.prefix, "Scripts", "pywin32_postinstall.py")
+             if not os.path.isfile(filename):
+                 raise RuntimeError("Can't find '%s'" % (filename,))
+             print("Executing post install script...")
+@@ -1388,18 +1444,25 @@ def my_new_compiler(**kw):
+     return orig_new_compiler(**kw)
+ 
+ # No way to cleanly wedge our compiler sub-class in.
+-from distutils import ccompiler, msvccompiler
++from distutils import ccompiler
+ orig_new_compiler = ccompiler.new_compiler
+ ccompiler.new_compiler = my_new_compiler
+ 
+-base_compiler = msvccompiler.MSVCCompiler
++if build_mingw32:
++    from distutils import cygwinccompiler
++    base_compiler = cygwinccompiler.Mingw32CCompiler
++else:
++    from distutils import msvccompiler
++    base_compiler = msvccompiler.MSVCCompiler
++
+ 
+ class my_compiler(base_compiler):
+     # Just one GUIDS.CPP and it gives trouble on mainwin too. Maybe I
+     # should just rename the file, but a case-only rename is likely to be
+     # worse!  This can probably go away once we kill the VS project files
+     # though, as we can just specify the lowercase name in the module def.
+-    _cpp_extensions = base_compiler._cpp_extensions + [".CPP"]
++    if not build_mingw32:
++        _cpp_extensions = base_compiler._cpp_extensions + [".CPP"]
+     src_extensions = base_compiler.src_extensions + [".CPP"]
+ 
+     def link(self,
+@@ -1411,17 +1474,41 @@ class my_compiler(base_compiler):
+               library_dirs=None,
+               runtime_library_dirs=None,
+               export_symbols=None,
+-              debug=0, *args, **kw):
+-        msvccompiler.MSVCCompiler.link( self,
+-                                        target_desc,
+-                                        objects,
+-                                        output_filename,
+-                                        output_dir,
+-                                        libraries,
+-                                        library_dirs,
+-                                        runtime_library_dirs,
+-                                        export_symbols,
+-                                        debug, *args, **kw)
++              debug=0, extra_preargs = None, *args, **kw):
++        if build_mingw32:
++            temp_dir = os.path.dirname(objects[0])
++            dll_name = os.path.splitext(os.path.basename(output_filename))[0]
++            lib_file = os.path.join(temp_dir, 'lib' + dll_name + ".a")
++            implib_arg="-Wl,--out-implib,%s" % lib_file
++
++            if extra_preargs:
++                extra_preargs.extend(implib_arg)
++            else:
++                extra_preargs = [implib_arg]
++
++            cygwinccompiler.Mingw32CCompiler.link( self,
++                                                   target_desc,
++                                                   objects,
++                                                   output_filename,
++                                                   output_dir,
++                                                   libraries,
++                                                   library_dirs,
++                                                   runtime_library_dirs,
++                                                   export_symbols,
++                                                   debug, extra_preargs,
++                                                   *args, **kw)
++        else:
++            msvccompiler.MSVCCompiler.link( self,
++                                            target_desc,
++                                            objects,
++                                            output_filename,
++                                            output_dir,
++                                            libraries,
++                                            library_dirs,
++                                            runtime_library_dirs,
++                                            export_symbols,
++                                            debug, *args, **kw)
++
+         # Here seems a good place to stamp the version of the built
+         # target.  Do this externally to avoid suddenly dragging in the
+         # modules needed by this process, and which we will soon try and
+@@ -1457,6 +1544,45 @@ class my_compiler(base_compiler):
+         if not ok:
+             log.info('Unable to import verstamp, no version info will be added')
+ 
++    if build_mingw32:
++        def _compile(self, obj, src, ext, cc_args, extra_postargs, pp_opts):
++            if ext == ".mc":
++                try:
++                    basename=os.path.basename(src)[:-3]
++                    outdir=os.path.dirname(obj)
++                    self.spawn(["windmc", "-h", outdir, "-r", outdir, src])
++                    self.spawn(["windres", "-i", 
++                                os.path.join(outdir, basename + ".rc"),
++                                "-o", obj])
++                except DistutilsExecError as msg:
++                    raise CompileError(msg)
++            else:
++                cygwinccompiler.Mingw32CCompiler._compile(self,
++                                                          obj, src, ext, cc_args,
++                                                          extra_postargs, pp_opts)
++
++        def object_filenames(self, source_filenames, strip_dir=0, output_dir=''):
++            unproc_src_names = []
++            obj_names = []
++            for src_name in source_filenames:
++                base, ext = os.path.splitext(src_name)
++                if ext==".mc":
++                    if unproc_src_names:
++                        obj_names.extend(cygwinccompiler.Mingw32CCompiler.\
++                            object_filenames(self, unproc_src_names,
++                                             strip_dir = strip_dir,
++                                             output_dir = output_dir))
++                        unproc_src_names = []
++                    obj_names.append (os.path.join(output_dir,
++                                      base + ext + self.obj_extension))
++                else:
++                    unproc_src_names.append(src_name)
++            if unproc_src_names:
++                obj_names.extend(cygwinccompiler.Mingw32CCompiler.\
++                    object_filenames(self, unproc_src_names, strip_dir = strip_dir,
++                                     output_dir = output_dir))
++            return obj_names
++
+ 
+ ################################################################
+ 
+@@ -1550,7 +1676,7 @@ for info in (
+             win32/src/win32crypt/PyCRYPTPROV.cpp
+             win32/src/win32crypt/PyCTL_CONTEXT.cpp
+             """),
+-        ("win32file", "", None, 0x0500, """
++        ("win32file", "wsock32 ws2_32" if build_mingw32 else "", None, 0x0500, """
+               win32/src/win32file.i
+               win32/src/win32file_comm.cpp
+               """),
+@@ -1607,7 +1733,7 @@ for info in (
+         sources = info[4].split()
+     extra_compile_args = []
+     ext = WinExt_win32(name,
+-                 libraries=lib_names,
++                 libraries=lib_names + (" pywintypes" if build_mingw32 else ""),
+                  extra_compile_args = extra_compile_args,
+                  windows_h_version = windows_h_ver,
+                  sources = sources,
+@@ -1620,7 +1746,7 @@ win32_extensions += [
+             sources = """
+                 win32\\src\\win32evtlog_messages.mc win32\\src\\win32evtlog.i
+                 """.split(),
+-                libraries="advapi32 oleaut32",
++                libraries="advapi32 oleaut32" + (" pywintypes" if build_mingw32 else ""),
+                 delay_load_libraries="wevtapi",
+                 windows_h_version=0x0600
+         ),
+@@ -1628,7 +1754,7 @@ win32_extensions += [
+            sources = """
+                 win32/src/win32apimodule.cpp win32/src/win32api_display.cpp
+                 """.split(),
+-           libraries="user32 advapi32 shell32 version",
++                 libraries="user32 advapi32 shell32 version" + (" pywintypes" if build_mingw32 else ""),
+            delay_load_libraries="powrprof",
+            windows_h_version=0x0500,
+         ),
+@@ -1638,7 +1764,7 @@ win32_extensions += [
+                 win32/src/win32gui.i
+                """.split(),
+            windows_h_version=0x0500,
+-           libraries="gdi32 user32 comdlg32 comctl32 shell32",
++           libraries="gdi32 user32 comdlg32 comctl32 shell32" + (" pywintypes" if build_mingw32 else ""),
+            define_macros = [("WIN32GUI", None)],
+         ),
+     # winxpgui is built from win32gui.i, but sets up different #defines before
+@@ -1648,7 +1774,7 @@ win32_extensions += [
+                 win32/src/winxpgui.rc win32/src/win32dynamicdialog.cpp
+                 win32/src/win32gui.i
+                """.split(),
+-           libraries="gdi32 user32 comdlg32 comctl32 shell32",
++           libraries="gdi32 user32 comdlg32 comctl32 shell32" + (" pywintypes" if build_mingw32 else ""),
+            windows_h_version=0x0500,
+            define_macros = [("WIN32GUI",None), ("WINXPGUI",None)],
+            extra_swig_commands=["-DWINXPGUI"],
+@@ -1656,7 +1782,7 @@ win32_extensions += [
+     # winxptheme
+     WinExt_win32("_winxptheme",
+            sources = ["win32/src/_winxptheme.i"],
+-           libraries="gdi32 user32 comdlg32 comctl32 shell32 Uxtheme",
++           libraries="gdi32 user32 comdlg32 comctl32 shell32 Uxtheme" + (" pywintypes" if build_mingw32 else ""),
+            windows_h_version=0x0500,
+         ),
+ ]
+@@ -1664,7 +1790,7 @@ win32_extensions += [
+     WinExt_win32('servicemanager',
+            sources = ["win32/src/PythonServiceMessages.mc", "win32/src/PythonService.cpp"],
+            extra_compile_args = ['-DPYSERVICE_BUILD_DLL'],
+-           libraries = "user32 ole32 advapi32 shell32",
++           libraries = "user32 ole32 advapi32 shell32" + (" pywintypes" if build_mingw32 else ""),
+            windows_h_version = 0x500,
+            unicode_mode=True,),
+ ]
+@@ -1695,7 +1821,8 @@ dirs = {
+ 
+ # The COM modules.
+ pythoncom = WinExt_system32('pythoncom',
+-                   sources=("""
++                   sources=((("%(win32com)s/initguid.cpp"  if build_mingw32 else "") +
++                        """
+                         %(win32com)s/dllmain.cpp            %(win32com)s/ErrorUtils.cpp
+                         %(win32com)s/MiscTypes.cpp          %(win32com)s/oleargs.cpp
+                         %(win32com)s/PyComHelpers.cpp       %(win32com)s/PyFactory.cpp
+@@ -1737,7 +1864,7 @@ pythoncom = WinExt_system32('pythoncom',
+                         %(win32com)s/extensions/PyICancelMethodCalls.cpp    %(win32com)s/extensions/PyIContext.cpp
+                         %(win32com)s/extensions/PyIEnumContextProps.cpp     %(win32com)s/extensions/PyIClientSecurity.cpp
+                         %(win32com)s/extensions/PyIServerSecurity.cpp
+-                        """ % dirs).split(),
++                        """) % dirs).split(),
+                    depends=("""
+                         %(win32com)s/include\\propbag.h          %(win32com)s/include\\PyComTypeObjects.h
+                         %(win32com)s/include\\PyFactory.h        %(win32com)s/include\\PyGConnectionPoint.h
+@@ -1763,7 +1890,7 @@ pythoncom = WinExt_system32('pythoncom',
+                         %(win32com)s/include\\PyIEnumContextProps.h     %(win32com)s/include\\PyIClientSecurity.h
+                         %(win32com)s/include\\PyIServerSecurity.h
+                         """ % dirs).split(),
+-                   libraries = "oleaut32 ole32 user32 urlmon",
++                   libraries = "oleaut32 ole32 user32 urlmon uuid" + (" pywintypes" if build_mingw32 else ""),
+                    export_symbol_file = 'com/win32com/src/PythonCOM.def',
+                    extra_compile_args = ['-DBUILD_PYTHONCOM'],
+                    pch_header = "stdafx.h",
+@@ -1788,7 +1915,7 @@ com_extensions += [
+                         %(adsi)s/PyIADs.cpp
+                         """ % dirs).split()),
+     WinExt_win32com('axcontrol', pch_header="axcontrol_pch.h",
+-                    sources=("""
++                    sources=(("""
+                         %(axcontrol)s/AXControl.cpp
+                         %(axcontrol)s/PyIOleControl.cpp          %(axcontrol)s/PyIOleControlSite.cpp
+                         %(axcontrol)s/PyIOleInPlaceActiveObject.cpp
+@@ -1799,10 +1926,11 @@ com_extensions += [
+                         %(axcontrol)s/PyIOleClientSite.cpp       %(axcontrol)s/PyIOleInPlaceSite.cpp
+                         %(axcontrol)s/PyIOleObject.cpp           %(axcontrol)s/PyIViewObject2.cpp
+                         %(axcontrol)s/PyIOleCommandTarget.cpp
+-                        """ % dirs).split()),
++                        """ + ("%(axcontrol)s/initguid.cpp" if build_mingw32 else "")) % dirs).split(),
++                        libraries="pythoncom pywintypes"),
+     WinExt_win32com('axscript',
+-                    sources=("""
+-                        %(axscript)s/AXScript.cpp
++                    sources=(("""
++                        %(axscript)s/AXScript.cpp                %(axscript)s/initguid.cpp
+                         %(axscript)s/GUIDS.CPP                   %(axscript)s/PyGActiveScript.cpp
+                         %(axscript)s/PyGActiveScriptError.cpp    %(axscript)s/PyGActiveScriptParse.cpp
+                         %(axscript)s/PyGActiveScriptSite.cpp     %(axscript)s/PyGObjectSafety.cpp
+@@ -1810,7 +1938,7 @@ com_extensions += [
+                         %(axscript)s/PyIActiveScriptParse.cpp    %(axscript)s/PyIActiveScriptParseProcedure.cpp
+                         %(axscript)s/PyIActiveScriptSite.cpp     %(axscript)s/PyIMultiInfos.cpp
+                         %(axscript)s/PyIObjectSafety.cpp         %(axscript)s/stdafx.cpp
+-                        """ % dirs).split(),
++                        """ + ("%(axscript)s/initguid.cpp" if build_mingw32 else "")) % dirs).split(),
+                     depends=("""
+                              %(axscript)s/AXScript.h
+                              %(axscript)s/guids.h                %(axscript)s/PyGActiveScriptError.h
+@@ -1820,7 +1948,8 @@ com_extensions += [
+                              """ % dirs).split(),
+                     extra_compile_args = ['-DPY_BUILD_AXSCRIPT'],
+                     implib_name="axscript",
+-                    pch_header = "stdafx.h"
++                    pch_header = "stdafx.h",
++                    libraries="pythoncom pywintypes" if build_mingw32 else ""
+     ),
+     WinExt_win32com('axdebug',
+             libraries="axscript",
+@@ -1870,17 +1999,17 @@ com_extensions += [
+                     %(axdebug)s/PyIRemoteDebugApplicationEvents.cpp
+                     %(axdebug)s/PyIRemoteDebugApplicationThread.cpp
+                     %(axdebug)s/stdafx.cpp
+-                     """ % dirs).split(),
+-    ),
++                     """ % dirs).split() ),
+     WinExt_win32com('internet', pch_header="internet_pch.h",
+-                    sources=("""
++                    sources=(("""
+                         %(internet)s/internet.cpp                   %(internet)s/PyIDocHostUIHandler.cpp
+                         %(internet)s/PyIHTMLOMWindowServices.cpp    %(internet)s/PyIInternetBindInfo.cpp
+                         %(internet)s/PyIInternetPriority.cpp        %(internet)s/PyIInternetProtocol.cpp
+                         %(internet)s/PyIInternetProtocolInfo.cpp    %(internet)s/PyIInternetProtocolRoot.cpp
+                         %(internet)s/PyIInternetProtocolSink.cpp    %(internet)s/PyIInternetSecurityManager.cpp
+-                    """ % dirs).split(),
+-                    depends=["%(internet)s/internet_pch.h" % dirs]),
++                    """ + ("%(internet)s/initguid.cpp"  if build_mingw32 else "")) % dirs).split(),
++                    depends=["%(internet)s/internet_pch.h" % dirs],
++                    libraries="pythoncom pywintypes" if build_mingw32 else ""),
+     WinExt_win32com('mapi', libraries="advapi32", pch_header="PythonCOM.h",
+                     include_dirs=["%(mapi)s/mapi_headers" % dirs],
+                     optional_headers=['edkmdb.h', 'edkguid.h'],
+@@ -1929,9 +2058,10 @@ com_extensions += [
+                                   %(mapi)s/mapi_stub_library/MapiStubLibrary.cpp
+                                   %(mapi)s/mapi_stub_library/StubUtils.cpp
+                                   """ % dirs).split()),
+-    WinExt_win32com('shell', libraries='shell32', pch_header="shell_pch.h",
++
++    WinExt_win32com('shell', libraries=('pythoncom pywintypes ' if build_mingw32 else '') + 'shell32', pch_header="shell_pch.h",
+                     windows_h_version = 0x600,
+-                    sources=("""
++                    sources=(("""
+                         %(shell)s/PyIActiveDesktop.cpp
+                         %(shell)s/PyIApplicationDestinations.cpp
+                         %(shell)s/PyIApplicationDocumentLists.cpp
+@@ -1956,8 +2086,6 @@ com_extensions += [
+                         %(shell)s/PyIEnumObjects.cpp
+                         %(shell)s/PyIEnumResources.cpp
+                         %(shell)s/PyIEnumShellItems.cpp
+-                        %(shell)s/PyIEmptyVolumeCache.cpp
+-                        %(shell)s/PyIEmptyVolumeCacheCallBack.cpp
+                         %(shell)s/PyIExplorerBrowser.cpp
+                         %(shell)s/PyIExplorerBrowserEvents.cpp
+                         %(shell)s/PyIExplorerCommand.cpp
+@@ -2002,8 +2130,9 @@ com_extensions += [
+                         %(shell)s/PyITransferSource.cpp
+                         %(shell)s/PyIUniformResourceLocator.cpp
+                         %(shell)s/shell.cpp
+-
+-                        """ % dirs).split()),
++                        """ + ("%(shell)s/initguid.cpp" if build_mingw32 else
++                               "%(shell)s/PyIEmptyVolumeCache.cpp %(shell)s/PyIEmptyVolumeCacheCallBack.cpp"))
++                             % dirs).split()),
+ 
+     WinExt_win32com('propsys', libraries='propsys', delay_load_libraries='shell32',
+                     unicode_mode=True,
+@@ -2031,9 +2160,8 @@ com_extensions += [
+                     implib_name="pypropsys",
+                     ),
+ 
+-
+-    WinExt_win32com('taskscheduler', libraries='mstask',
+-                    sources=("""
++    WinExt_win32com('taskscheduler', libraries='mstask' + (' pythoncom pywintypes'  if build_mingw32 else ''),
++                    sources=(("""
+                         %(taskscheduler)s/taskscheduler.cpp
+                         %(taskscheduler)s/PyIProvideTaskPage.cpp
+                         %(taskscheduler)s/PyIScheduledWorkItem.cpp
+@@ -2041,7 +2169,7 @@ com_extensions += [
+                         %(taskscheduler)s/PyITaskScheduler.cpp
+                         %(taskscheduler)s/PyITaskTrigger.cpp
+ 
+-                        """ % dirs).split()),
++                        """ + ("%(taskscheduler)s/initguid.cpp" if build_mingw32 else ""))% dirs).split()),
+     WinExt_win32com('bits', libraries='Bits', pch_header="bits_pch.h",
+                     sources=("""
+                         %(bits)s/bits.cpp
+@@ -2077,12 +2205,12 @@ com_extensions += [
+                         %(directsound)s/PyIDirectSoundCaptureBuffer.h %(directsound)s/PyIDirectSoundNotify.h
+                         """ % dirs).split(),
+                     optional_headers = ['dsound.h'],
+-                    libraries='user32 dsound dxguid'),
+-    WinExt_win32com('authorization', libraries='aclui advapi32',
++                    libraries=('pythoncom pywintypes ' if build_mingw32 else '') + 'user32 dsound dxguid uuid'),
++    WinExt_win32com('authorization', libraries=('pythoncom pywintypes ' if build_mingw32 else '') + 'aclui advapi32',
+                     sources=("""
+                         %(authorization)s/authorization.cpp
+                         %(authorization)s/PyGSecurityInformation.cpp
+-                        """ % dirs).split()),
++                        """ % dirs).split())
+ ]
+ 
+ pythonwin_extensions = [
+@@ -2253,20 +2381,24 @@ other_extensions.append(
+ W32_exe_files = [
+     WinExt_win32("pythonservice",
+          sources=[os.path.join("win32", "src", s) for s in
+-                  "PythonService.cpp PythonService.rc".split()],
++                  (("PythonServiceMessages.mc " if build_mingw32 else "") + "PythonService.cpp PythonService.rc").split()],
+          unicode_mode = True,
+-         extra_link_args=["/SUBSYSTEM:CONSOLE"],
+-         libraries = "user32 advapi32 ole32 shell32"),
+-    WinExt_pythonwin("Pythonwin",
+-        sources = [
+-            "Pythonwin/pythonwin.cpp",
+-            "Pythonwin/pythonwin.rc",
+-            "Pythonwin/stdafxpw.cpp",
+-            ],
+-        extra_link_args=["/SUBSYSTEM:WINDOWS"],
+-        optional_headers=['afxres.h']),
++         extra_link_args=[] if build_mingw32 else ["/SUBSYSTEM:CONSOLE"],
++         libraries = ("pywintypes " if build_mingw32 else "") + "user32 advapi32 ole32 shell32")
+ ]
+ 
++if not build_mingw32:
++    W32_exe_files.append(
++        WinExt_pythonwin("Pythonwin",
++            sources = [
++                "Pythonwin/pythonwin.cpp",
++                "Pythonwin/pythonwin.rc",
++                "Pythonwin/stdafxpw.cpp",
++            ],
++            extra_link_args=["/SUBSYSTEM:WINDOWS"],
++            optional_headers=['afxres.h'])
++        )
++
+ # Special definitions for SWIG.
+ swig_interface_parents = {
+     # source file base,     "base class" for generated COM support
+@@ -2415,7 +2547,10 @@ packages=['win32com',
+           ]
+ 
+ py_modules = expand_modules("win32\\lib")
+-ext_modules = win32_extensions + com_extensions + pythonwin_extensions + \
++if build_mingw32:
++    ext_modules = win32_extensions + com_extensions + other_extensions
++else:
++    ext_modules = win32_extensions + com_extensions + pythonwin_extensions + \
+                     other_extensions
+ 
+ # Build a map of DLL base addresses.  According to Python's PC\dllbase_nt.txt,
+diff --git a/win32/src/PerfMon/perfmondata.cpp b/win32/src/PerfMon/perfmondata.cpp
+index 23e7557..c456d89 100644
+--- a/win32/src/PerfMon/perfmondata.cpp
++++ b/win32/src/PerfMon/perfmondata.cpp
+@@ -89,10 +89,19 @@ PPERF_COUNTER_BLOCK pCounterBlock;
+ //      these are used to insure that the data collection functions
+ //      accessed by Perflib will have the correct calling format.
+ //
++
++#if defined(__MINGW32__)
++extern "C" {
++#endif
++
+ PM_OPEN_PROC   OpenPerformanceData;
+ PM_COLLECT_PROC    CollectPerformanceData;
+ PM_CLOSE_PROC  ClosePerformanceData;
+ 
++#if defined(__MINGW32__)
++}
++#endif
++
+ TCHAR szFullModulePath[MAX_PATH];
+ TCHAR szModuleName[MAX_PATH]; // will point into the buffer above.
+ 
+@@ -130,6 +139,9 @@ BOOL WINAPI DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID lpReserved)
+ 
+ 
+ 
++#if defined(__MINGW32__)
++extern "C"
++#endif
+ DWORD APIENTRY OpenPerformanceData( LPWSTR lpDeviceNames )
+ /*++
+     Routine Description:
+@@ -278,6 +290,9 @@ OpenExitPoint:
+ 	return status;
+ }
+ 
++#if defined(__MINGW32__)
++extern "C"
++#endif
+ DWORD APIENTRY CollectPerformanceData(
+     IN      LPWSTR  lpValueName,
+ 	IN OUT  LPVOID  *lppData,
+@@ -379,6 +394,9 @@ Arguments:   IN       LPWSTR   lpValueName
+     return ERROR_SUCCESS;
+ }
+ 
++#if defined(__MINGW32__)
++extern "C"
++#endif
+ DWORD APIENTRY ClosePerformanceData()
+ /*++
+ Routine Description:
+@@ -445,7 +463,11 @@ HANDLE MonOpenEventLog (const TCHAR *szSourceName)
+ --*/
+ {
+     HKEY hAppKey;
++#if defined(__MINGW32__)
++    TCHAR LogLevelKeyName[] = _T("SOFTWARE\\Microsoft\\Windows_NT\\CurrentVersion\\Perflib");
++#else
+     TCHAR LogLevelKeyName[] = _T("SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Perflib");
++#endif
+ 
+     TCHAR LogLevelValueName[] = _T("EventLogLevel");
+ 	LONG lStatus;
+diff --git a/win32/src/PySECURITY_DESCRIPTOR.cpp b/win32/src/PySECURITY_DESCRIPTOR.cpp
+index 218daf9..2873603 100644
+--- a/win32/src/PySECURITY_DESCRIPTOR.cpp
++++ b/win32/src/PySECURITY_DESCRIPTOR.cpp
+@@ -6,6 +6,10 @@
+ #include "PySecurityObjects.h"
+ #include "structmember.h"
+ 
++#if defined(__MINGW32__)
++#include <algorithm>
++#endif
++
+ #ifndef NO_PYWINTYPES_SECURITY
+ BOOL (WINAPI *setsecuritydescriptorcontrol)(PSECURITY_DESCRIPTOR, SECURITY_DESCRIPTOR_CONTROL, SECURITY_DESCRIPTOR_CONTROL)=NULL;
+ 
+@@ -786,7 +790,11 @@ PySECURITY_DESCRIPTOR::PySECURITY_DESCRIPTOR(Py_ssize_t cb /*= 0*/)
+ {
+ 	ob_type = &PySECURITY_DESCRIPTORType;
+ 	_Py_NewReference(this);
++#if defined(__MINGW32__)
++	cb = std::max(cb, static_cast<Py_ssize_t>(SECURITY_DESCRIPTOR_MIN_LENGTH));
++#else
+ 	cb = max(cb, SECURITY_DESCRIPTOR_MIN_LENGTH);
++#endif
+ 	PSECURITY_DESCRIPTOR psd = malloc(cb);
+ 	this->m_psd=NULL;
+ 	if (::InitializeSecurityDescriptor(psd, SECURITY_DESCRIPTOR_REVISION))
+diff --git a/win32/src/PyWinTypes.h b/win32/src/PyWinTypes.h
+index 00ac8a1..a5fc23e 100644
+--- a/win32/src/PyWinTypes.h
++++ b/win32/src/PyWinTypes.h
+@@ -393,8 +393,13 @@ PYWINTYPES_EXPORT PyObject *PyWinObject_FromULARGE_INTEGER(ULARGE_INTEGER &val);
+ // We also happen to know a LARGE_INTEGER is an __int64, so do it the easy way
+ #define PyWinObject_AsPY_LONG_LONG(ob, pResult) PyWinObject_AsLARGE_INTEGER((ob), (LARGE_INTEGER *)(pResult))
+ #define PyWinObject_AsUPY_LONG_LONG(ob, pResult) PyWinObject_AsULARGE_INTEGER((ob), (ULARGE_INTEGER *)(pResult))
++#if defined(__MINGW32__)
++#define PyWinObject_FromPY_LONG_LONG(val) PyWinObject_FromLARGE_INTEGER(val)
++#define PyWinObject_FromUPY_LONG_LONG(val) PyWinObject_FromULARGE_INTEGER(val)
++#else
+ #define PyWinObject_FromPY_LONG_LONG(val) PyWinObject_FromLARGE_INTEGER((LARGE_INTEGER)val)
+ #define PyWinObject_FromUPY_LONG_LONG(val) PyWinObject_FromULARGE_INTEGER((ULARGE_INTEGER)val)
++#endif
+ 
+ // A DWORD_PTR and ULONG_PTR appear to mean "integer long enough to hold a pointer"
+ // It is *not* actually a pointer (but is the same size as a pointer)
+@@ -797,7 +802,7 @@ private:
+ 
+ // A helper for simple exception handling.
+ // try/__try
+-#ifdef MAINWIN
++#if defined(__MINGW32__) || defined(MAINWIN)
+ #define PYWINTYPES_TRY try
+ #else
+ #define PYWINTYPES_TRY __try
+diff --git a/win32/src/PyWinTypesmodule.cpp b/win32/src/PyWinTypesmodule.cpp
+index e136fff..77e10a4 100644
+--- a/win32/src/PyWinTypesmodule.cpp
++++ b/win32/src/PyWinTypesmodule.cpp
+@@ -1140,7 +1140,11 @@ BOOL WINAPI DllMain(HANDLE hInstance, DWORD dwReason, LPVOID lpReserved)
+ }
+ 
+ // Function to format a python traceback into a character string.
++#if defined(__MINGW32__)
++#define GPEM_ERROR(what) {errorMsg = "<Error getting traceback - " what ">";goto done;}
++#else
+ #define GPEM_ERROR(what) {errorMsg = "<Error getting traceback - " ## what ## ">";goto done;}
++#endif
+ char *GetPythonTraceback(PyObject *exc_type, PyObject *exc_value, PyObject *exc_tb)
+ {
+ 	// Sleep (30000); // Time enough to attach the debugger (barely)
+diff --git a/win32/src/PythonService.cpp b/win32/src/PythonService.cpp
+index c7b7531..8a9121d 100644
+--- a/win32/src/PythonService.cpp
++++ b/win32/src/PythonService.cpp
+@@ -302,7 +302,11 @@ static PyObject *PySetEventSourceName(PyObject *self, PyObject *args)
+ 	if (!PyWinObject_AsTCHAR(obName, &msg))
+ 		return NULL;
+ 	_tcsncpy(g_szEventSourceName, msg,
++#if defined(__MINGW32__)
++			 sizeof(g_szEventSourceName)/sizeof(TCHAR));
++#else
+ 			 sizeof g_szEventSourceName/sizeof TCHAR);
++#endif
+ 	PyWinObject_FreeTCHAR(msg);
+ 	g_bRegisteredEventSource = FALSE; // so this name re-registered.
+ 	if (registerNow)
+@@ -680,10 +684,18 @@ BOOL PythonService_Initialize( const TCHAR *evtsrc_name, const TCHAR *evtsrc_fil
+ {
+ 	if (evtsrc_name && *evtsrc_name)
+ 		_tcsncpy(g_szEventSourceName, evtsrc_name,
++#if defined(__MINGW32__)
++				 sizeof(g_szEventSourceName)/sizeof(TCHAR));
++#else
+ 				 sizeof g_szEventSourceName/sizeof TCHAR);
++#endif
+ 	if (evtsrc_file && *evtsrc_file)
+ 		_tcsncpy(g_szEventSourceFileName, evtsrc_file,
++#if defined(__MINGW32__)
++				 sizeof(g_szEventSourceFileName)/sizeof(TCHAR));
++#else
+ 				 sizeof g_szEventSourceFileName/sizeof TCHAR);
++#endif
+ 	return TRUE;
+ }
+ 
+@@ -1443,7 +1455,11 @@ static void CheckRegisterEventSourceFile()
+ 
+ 	if (!g_szEventSourceFileName[0])
+ 		GetModuleFileName(g_hdll, g_szEventSourceFileName,
++#if defined(__MINGW32__)
++		                  sizeof(g_szEventSourceFileName)/sizeof(TCHAR));
++#else
+ 		                  sizeof g_szEventSourceFileName/sizeof TCHAR);
++#endif
+ 
+ 	HKEY hkey;
+ 	TCHAR keyName[MAX_PATH];
+@@ -1549,7 +1565,11 @@ BOOL WINAPI DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID lpReserved)
+ #else // PYSERVICE_BUILD_DLL
+ // Our EXE entry point.
+ 
++#if defined(__MINGW32__)
++extern "C" int main(int argc, TCHAR **argv)
++#else
+ int _tmain(int argc, TCHAR **argv)
++#endif
+ {
+ 	PyObject *module, *f;
+ 	PyThreadState *threadState;
+diff --git a/win32/src/PythonServiceMessages.mc b/win32/src/PythonServiceMessages.mc
+index ef26675..c8787a4 100644
+--- a/win32/src/PythonServiceMessages.mc
++++ b/win32/src/PythonServiceMessages.mc
+@@ -134,6 +134,7 @@ MessageId=0x7
+ Severity=Error
+ SymbolicName=E_UNUSED2
+ Language=English
++%1
+ .
+ 
+ MessageId=0x8
+diff --git a/win32/src/odbc.cpp b/win32/src/odbc.cpp
+index c58aef5..9d3dc35 100644
+--- a/win32/src/odbc.cpp
++++ b/win32/src/odbc.cpp
+@@ -18,6 +18,10 @@
+ #include "PyWinObjects.h"
+ #include "structmember.h"
+ 
++#if defined(__MINGW32__)
++#include <algorithm>
++#endif
++
+ #include <sql.h>
+ #include <sqlext.h>
+ 
+@@ -105,96 +109,10 @@ static cursorObject *cursor(PyObject *o)
+ }
+ 
+ static void cursorDealloc(PyObject *self);
+-PyMethodDef cursorMethods[];
+-PyMemberDef cursorMembers[];
+ 
+-static PyTypeObject Cursor_Type =
+-{
+-	PYWIN_OBJECT_HEAD
+-	"odbccur",				/*tp_name */
+-	sizeof(cursorObject),	/*tp_basicsize */
+-	0,						/*tp_itemsize */
+-	cursorDealloc,			/*tp_dealloc */
+-	0,						/*tp_print */
+-	0,						/*tp_getattr */
+-	0,						/*tp_setattr */
+-	0,						/*tp_compare */
+-	0,						/*tp_repr */
+-	0,						/*tp_as_number */
+-	0,						/* tp_as_sequence */
+-	0,						/* tp_as_mapping */
+-	0,						/* tp_hash */
+-	0,						/* tp_call */
+-	0,						/*tp_str */
+-	PyObject_GenericGetAttr,	/* tp_getattro dbiGetAttr */
+-	PyObject_GenericSetAttr,	/* tp_setattro */
+-	0,						/*tp_as_buffer*/
+-	Py_TPFLAGS_DEFAULT,		/* tp_flags */
+-	0,						/* tp_doc */
+-	0,						/* tp_traverse */
+-	0,						/* tp_clear */
+-	0,						/* tp_richcompare */
+-	0,						/* tp_weaklistoffset */
+-	0,						/* tp_iter */
+-	0,						/* tp_iternext */
+-	cursorMethods,			/* tp_methods */
+-	cursorMembers,			/* tp_members */
+-	0,						/* tp_getset */
+-	0,						/* tp_base */
+-	0,						/* tp_dict */
+-	0,						/* tp_descr_get */
+-	0,						/* tp_descr_set */
+-	0,						/* tp_dictoffset */
+-	0,						/* tp_init */
+-	0,						/* tp_alloc */
+-	0,						/* tp_new */
+-};
+ 
+ 
+ static void connectionDealloc(PyObject *self);
+-PyMethodDef connectionMethods[];
+-PyMemberDef connectionMembers[];
+-static PyTypeObject Connection_Type =
+-{
+-	PYWIN_OBJECT_HEAD
+-	"odbcconn",				/*tp_name */
+-	sizeof (connectionObject),	/*tp_basicsize */
+-	0,						/*tp_itemsize */
+-	connectionDealloc,		/*tp_dealloc */
+-	0,						/*tp_print */
+-	0,						/*tp_getattr */
+-	0,						/*tp_setattr */
+-	0,						/*tp_compare */
+-	0,						/*tp_repr */
+-	0,						/*tp_as_number */
+-	0,						/* tp_as_sequence */
+-	0,						/* tp_as_mapping */
+-	0,						/* tp_hash */
+-	0,						/* tp_call */
+-	0,						/*tp_str */
+-	PyObject_GenericGetAttr,	/* tp_getattro dbiGetAttr */
+-	PyObject_GenericSetAttr,	/* tp_setattro */
+-	0,						/*tp_as_buffer*/
+-	Py_TPFLAGS_DEFAULT,		/* tp_flags */
+-	0,						/* tp_doc */
+-	0,						/* tp_traverse */
+-	0,						/* tp_clear */
+-	0,						/* tp_richcompare */
+-	0,						/* tp_weaklistoffset */
+-	0,						/* tp_iter */
+-	0,						/* tp_iternext */
+-	connectionMethods,		/* tp_methods */
+-	connectionMembers,		/* tp_members */
+-	0,						/* tp_getset */
+-	0,						/* tp_base */
+-	0,						/* tp_dict */
+-	0,						/* tp_descr_get */
+-	0,						/* tp_descr_set */
+-	0,						/* tp_dictoffset */
+-	0,						/* tp_init */
+-	0,						/* tp_alloc */
+-	0,						/* tp_new */
+-};
+ 
+ static int unsuccessful(RETCODE rc)
+ {
+@@ -334,144 +252,6 @@ static int attemptReconnect(cursorObject *cur)
+ }
+ 
+ 
+-/* @pymethod |connection|setautocommit|Sets the autocommit mode. */
+-static PyObject *odbcSetAutoCommit(PyObject *self, PyObject *args)
+-{
+-	int c;
+-	connectionObject *conn;
+-	/* @pyparm int|c||The boolean autocommit mode. */
+-	if (!PyArg_ParseTuple(args, "i",&c))
+-		return NULL;
+-	conn=connection(self);
+-	if (c==0)
+-	{
+-		if (unsuccessful(SQLSetConnectOption(
+-			conn->hdbc,
+-			SQL_AUTOCOMMIT,
+-			SQL_AUTOCOMMIT_OFF)))
+-		{
+-			connectionError(conn, _T("SETAUTOCOMMIT"));
+-			return NULL;
+-		}
+-	}
+-	else
+-	{
+-		if (unsuccessful(SQLSetConnectOption(
+-			conn->hdbc,
+-			SQL_AUTOCOMMIT,
+-			SQL_AUTOCOMMIT_ON)))
+-		{
+-			connectionError(conn, _T("SETAUTOCOMMIT"));
+-			return NULL;
+-		};
+-	}
+-
+-	Py_INCREF(Py_None);
+-	return Py_None;
+-}
+-
+-
+-/* @pymethod |connection|commit|Commits a transaction. */
+-static PyObject *odbcCommit(PyObject *self, PyObject *args)
+-{
+-	RETCODE rc;
+-	Py_BEGIN_ALLOW_THREADS
+-	rc = SQLTransact(
+-		Env,
+-		connection(self)->hdbc,
+-		SQL_COMMIT);
+-	Py_END_ALLOW_THREADS
+-	if (unsuccessful(rc))
+-	{
+-		connectionError(connection(self), _T("COMMIT"));
+-		return 0;
+-	}
+-	else
+-	{
+-		Py_INCREF(Py_None);
+-		return Py_None;
+-	}
+-}
+-
+-/* @pymethod |connection|rollback|Rollsback a transaction. */
+-static PyObject *odbcRollback(PyObject *self, PyObject *args)
+-{
+-	RETCODE rc;
+-	Py_BEGIN_ALLOW_THREADS
+-	rc = SQLTransact(
+-		Env,
+-		connection(self)->hdbc,
+-		SQL_ROLLBACK);
+-	Py_END_ALLOW_THREADS
+-	if (unsuccessful(rc))
+-	{
+-		connectionError(connection(self), _T("ROLLBACK"));
+-		return 0;
+-	}
+-	else {
+-		Py_INCREF(Py_None);
+-		return Py_None;
+-	}
+-}
+-
+-/* @pymethod |connection|cursor|Creates a <o cursor> object */
+-static PyObject *odbcCursor(PyObject *self, PyObject *args)
+-{
+-	connectionObject *conn = connection(self);
+-	if (conn->connected == 0)
+-	{
+-		if (doConnect(conn))
+-		{
+-			return 0;
+-		}
+-	}
+-
+-	cursorObject *cur = PyObject_New(cursorObject, &Cursor_Type);
+-	if (cur == NULL)
+-		return NULL;
+-
+-	cur->outputVars = 0;
+-	cur->inputVars = 0;
+-	cur->description = 0;
+-	cur->max_width = 65536L;
+-	cur->my_conx = 0;
+-	cur->hstmt=NULL;
+-	cur->cursorError=odbcError;
+-	Py_INCREF(odbcError);
+-	if (unsuccessful(SQLAllocStmt(conn->hdbc, &cur->hstmt)))
+-	{
+-		connectionError(cur->my_conx, _T("OPEN"));
+-		Py_DECREF(cur);
+-		return NULL;
+-	}
+-	cur->my_conx = conn;
+-	cur->connect_id = cur->my_conx->connect_id;
+-	Py_INCREF(self); /* the cursors owns a reference to the connection */
+-	return (PyObject*) cur;
+-}
+-
+-/* @pymethod |connection|close|Closes the connection. */
+-static PyObject *odbcClose(PyObject *self, PyObject *args)
+-{
+-  Py_INCREF(Py_None);
+-  return Py_None;
+-}
+-
+-/* @object connection|An object representing an ODBC connection */
+-static struct PyMethodDef connectionMethods[] = {
+-	{ "setautocommit", odbcSetAutoCommit, 1 }, /* @pymeth setautocommit|Sets the autocommit mode. */
+-	{ "commit", odbcCommit, 1 } , /* @pymeth commit|Commits a transaction. */
+-	{ "rollback", odbcRollback, 1 } , /* @pymeth rollback|Rollsback a transaction. */
+-	{ "cursor", odbcCursor, 1 } , /* @pymeth cursor|Creates a <o cursor> object */
+-	{ "close", odbcClose, 1 } , /* @pymeth close|Closes the connection. */
+-	{0,     0}
+-};
+-
+-static PyMemberDef connectionMembers[] = {
+-	{"error", T_OBJECT, offsetof(connectionObject, connectionError), READONLY},
+-	{NULL}
+-};
+-
+ static void connectionDealloc(PyObject *self)
+ {
+ 	Py_XDECREF(connection(self)->connectionError);
+@@ -1192,21 +972,41 @@ static int display_size(short coltype, int collen, const TCHAR *colname)
+     case SQL_DATE:
+     case SQL_TIMESTAMP:
+     case SQL_BIT:
++#if defined(__MINGW32__)
++      return(std::max(collen, (int)_tcslen(colname)));
++#else
+       return(max(collen, (int)_tcslen(colname)));
++#endif
+     case SQL_SMALLINT:
+     case SQL_INTEGER:
+     case SQL_TINYINT:
++#if defined(__MINGW32__)
++      return(std::max(collen+1, (int)_tcslen(colname)));
++#else
+       return(max(collen+1, (int)_tcslen(colname)));
++#endif
+     case SQL_DECIMAL:
+     case SQL_NUMERIC:
++#if defined(__MINGW32__)
++      return(std::max(collen+2, (int)_tcslen(colname)));
++#else
+       return(max(collen+2, (int)_tcslen(colname)));
++#endif
+     case SQL_REAL:
+     case SQL_FLOAT:
+     case SQL_DOUBLE:
++#if defined(__MINGW32__)
++      return(std::max(20, (int)_tcslen(colname)));
++#else
+       return(max(20, (int)_tcslen(colname)));
++#endif
+     case SQL_BINARY:
+     case SQL_VARBINARY:
++#if defined(__MINGW32__)
++      return(std::max(2*collen, (int)_tcslen(colname)));
++#else
+       return(max(2*collen, (int)_tcslen(colname)));
++#endif
+     case SQL_LONGVARBINARY:
+     case SQL_LONGVARCHAR:
+     default:
+@@ -1814,6 +1614,226 @@ static PyMemberDef cursorMembers[] = {
+ 	{NULL}
+ };
+ 
++static PyTypeObject Cursor_Type =
++{
++	PYWIN_OBJECT_HEAD
++	"odbccur",				/*tp_name */
++	sizeof(cursorObject),	/*tp_basicsize */
++	0,						/*tp_itemsize */
++	cursorDealloc,			/*tp_dealloc */
++	0,						/*tp_print */
++	0,						/*tp_getattr */
++	0,						/*tp_setattr */
++	0,						/*tp_compare */
++	0,						/*tp_repr */
++	0,						/*tp_as_number */
++	0,						/* tp_as_sequence */
++	0,						/* tp_as_mapping */
++	0,						/* tp_hash */
++	0,						/* tp_call */
++	0,						/*tp_str */
++	PyObject_GenericGetAttr,	/* tp_getattro dbiGetAttr */
++	PyObject_GenericSetAttr,	/* tp_setattro */
++	0,						/*tp_as_buffer*/
++	Py_TPFLAGS_DEFAULT,		/* tp_flags */
++	0,						/* tp_doc */
++	0,						/* tp_traverse */
++	0,						/* tp_clear */
++	0,						/* tp_richcompare */
++	0,						/* tp_weaklistoffset */
++	0,						/* tp_iter */
++	0,						/* tp_iternext */
++	cursorMethods,			/* tp_methods */
++	cursorMembers,			/* tp_members */
++	0,						/* tp_getset */
++	0,						/* tp_base */
++	0,						/* tp_dict */
++	0,						/* tp_descr_get */
++	0,						/* tp_descr_set */
++	0,						/* tp_dictoffset */
++	0,						/* tp_init */
++	0,						/* tp_alloc */
++	0,						/* tp_new */
++};
++/* @pymethod |connection|setautocommit|Sets the autocommit mode. */
++static PyObject *odbcSetAutoCommit(PyObject *self, PyObject *args)
++{
++	int c;
++	connectionObject *conn;
++	/* @pyparm int|c||The boolean autocommit mode. */
++	if (!PyArg_ParseTuple(args, "i",&c))
++		return NULL;
++	conn=connection(self);
++	if (c==0)
++	{
++		if (unsuccessful(SQLSetConnectOption(
++			conn->hdbc,
++			SQL_AUTOCOMMIT,
++			SQL_AUTOCOMMIT_OFF)))
++		{
++			connectionError(conn, _T("SETAUTOCOMMIT"));
++			return NULL;
++		}
++	}
++	else
++	{
++		if (unsuccessful(SQLSetConnectOption(
++			conn->hdbc,
++			SQL_AUTOCOMMIT,
++			SQL_AUTOCOMMIT_ON)))
++		{
++			connectionError(conn, _T("SETAUTOCOMMIT"));
++			return NULL;
++		};
++	}
++
++	Py_INCREF(Py_None);
++	return Py_None;
++}
++
++
++/* @pymethod |connection|commit|Commits a transaction. */
++static PyObject *odbcCommit(PyObject *self, PyObject *args)
++{
++	RETCODE rc;
++	Py_BEGIN_ALLOW_THREADS
++	rc = SQLTransact(
++		Env,
++		connection(self)->hdbc,
++		SQL_COMMIT);
++	Py_END_ALLOW_THREADS
++	if (unsuccessful(rc))
++	{
++		connectionError(connection(self), _T("COMMIT"));
++		return 0;
++	}
++	else
++	{
++		Py_INCREF(Py_None);
++		return Py_None;
++	}
++}
++
++/* @pymethod |connection|rollback|Rollsback a transaction. */
++static PyObject *odbcRollback(PyObject *self, PyObject *args)
++{
++	RETCODE rc;
++	Py_BEGIN_ALLOW_THREADS
++	rc = SQLTransact(
++		Env,
++		connection(self)->hdbc,
++		SQL_ROLLBACK);
++	Py_END_ALLOW_THREADS
++	if (unsuccessful(rc))
++	{
++		connectionError(connection(self), _T("ROLLBACK"));
++		return 0;
++	}
++	else {
++		Py_INCREF(Py_None);
++		return Py_None;
++	}
++}
++
++/* @pymethod |connection|cursor|Creates a <o cursor> object */
++static PyObject *odbcCursor(PyObject *self, PyObject *args)
++{
++	connectionObject *conn = connection(self);
++	if (conn->connected == 0)
++	{
++		if (doConnect(conn))
++		{
++			return 0;
++		}
++	}
++
++	cursorObject *cur = PyObject_New(cursorObject, &Cursor_Type);
++	if (cur == NULL)
++		return NULL;
++
++	cur->outputVars = 0;
++	cur->inputVars = 0;
++	cur->description = 0;
++	cur->max_width = 65536L;
++	cur->my_conx = 0;
++	cur->hstmt=NULL;
++	cur->cursorError=odbcError;
++	Py_INCREF(odbcError);
++	if (unsuccessful(SQLAllocStmt(conn->hdbc, &cur->hstmt)))
++	{
++		connectionError(cur->my_conx, _T("OPEN"));
++		Py_DECREF(cur);
++		return NULL;
++	}
++	cur->my_conx = conn;
++	cur->connect_id = cur->my_conx->connect_id;
++	Py_INCREF(self); /* the cursors owns a reference to the connection */
++	return (PyObject*) cur;
++}
++
++/* @pymethod |connection|close|Closes the connection. */
++static PyObject *odbcClose(PyObject *self, PyObject *args)
++{
++  Py_INCREF(Py_None);
++  return Py_None;
++}
++
++/* @object connection|An object representing an ODBC connection */
++static struct PyMethodDef connectionMethods[6] = {
++	{ "setautocommit", odbcSetAutoCommit, 1 }, /* @pymeth setautocommit|Sets the autocommit mode. */
++	{ "commit", odbcCommit, 1 } , /* @pymeth commit|Commits a transaction. */
++	{ "rollback", odbcRollback, 1 } , /* @pymeth rollback|Rollsback a transaction. */
++	{ "cursor", odbcCursor, 1 } , /* @pymeth cursor|Creates a <o cursor> object */
++	{ "close", odbcClose, 1 } , /* @pymeth close|Closes the connection. */
++	{0,     0}
++};
++
++static PyMemberDef connectionMembers[2] = {
++	{"error", T_OBJECT, offsetof(connectionObject, connectionError), READONLY},
++	{NULL}
++};
++
++static PyTypeObject Connection_Type =
++{
++	PYWIN_OBJECT_HEAD
++	"odbcconn",				/*tp_name */
++	sizeof (connectionObject),	/*tp_basicsize */
++	0,						/*tp_itemsize */
++	connectionDealloc,		/*tp_dealloc */
++	0,						/*tp_print */
++	0,						/*tp_getattr */
++	0,						/*tp_setattr */
++	0,						/*tp_compare */
++	0,						/*tp_repr */
++	0,						/*tp_as_number */
++	0,						/* tp_as_sequence */
++	0,						/* tp_as_mapping */
++	0,						/* tp_hash */
++	0,						/* tp_call */
++	0,						/*tp_str */
++	PyObject_GenericGetAttr,	/* tp_getattro dbiGetAttr */
++	PyObject_GenericSetAttr,	/* tp_setattro */
++	0,						/*tp_as_buffer*/
++	Py_TPFLAGS_DEFAULT,		/* tp_flags */
++	0,						/* tp_doc */
++	0,						/* tp_traverse */
++	0,						/* tp_clear */
++	0,						/* tp_richcompare */
++	0,						/* tp_weaklistoffset */
++	0,						/* tp_iter */
++	0,						/* tp_iternext */
++	connectionMethods,		/* tp_methods */
++	connectionMembers,		/* tp_members */
++	0,						/* tp_getset */
++	0,						/* tp_base */
++	0,						/* tp_dict */
++	0,						/* tp_descr_get */
++	0,						/* tp_descr_set */
++	0,						/* tp_dictoffset */
++	0,						/* tp_init */
++	0,						/* tp_alloc */
++	0,						/* tp_new */
++};
+ static void parseInfo(connectionObject *conn, const TCHAR *c)
+ {
+ 	TCHAR *p;
+diff --git a/win32/src/win32apimodule.cpp b/win32/src/win32apimodule.cpp
+index f7e36b1..dd5223f 100644
+--- a/win32/src/win32apimodule.cpp
++++ b/win32/src/win32apimodule.cpp
+@@ -817,12 +817,16 @@ PyFormatMessageA(PyObject *self, PyObject *args)
+ 	
+ 	{
+ 	PyW32_BEGIN_ALLOW_THREADS
++#if !defined(__MINGW32__)
+ 	__try{
++#endif
+ 		lrc = ::FormatMessageA(flags, pSource, msgId, langId, (LPSTR)&resultBuf, 0, (va_list *)pInserts );
++#if !defined(__MINGW32__)
+ 		}
+ 	__except (GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH){
+ 		baccessviolation=TRUE;
+ 		}
++#endif
+ 	PyW32_END_ALLOW_THREADS
+ 	}
+ 
+@@ -927,12 +931,16 @@ PyFormatMessageW(PyObject *self, PyObject *args)
+ 
+ 	{
+ 	PyW32_BEGIN_ALLOW_THREADS
++#if !defined(__MINGW32__)
+ 	__try{
++#endif
+ 		lrc = ::FormatMessageW(flags, pSource, msgId, langId, (LPWSTR)&resultBuf, 0, (va_list *)pInserts );
++#if !defined(__MINGW32__)
+ 		}
+ 	__except (GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH){
+ 		baccessviolation=TRUE;
+ 		}
++#endif 
+ 	PyW32_END_ALLOW_THREADS
+ 	}
+ 
+@@ -5774,8 +5782,11 @@ static PyObject *PyApply(PyObject *self, PyObject *args)
+ 	}
+ 	PyThreadState *stateSave = PyThreadState_Swap(NULL);
+ 	PyThreadState_Swap(stateSave);
++#if !defined(__MINGW32__)
+ 	_try {
++#endif
+ 		ret = PyObject_CallObject(obFunc, obArgs);
++#if !defined(__MINGW32__)
+ 	}
+ 	_except( PyApplyExceptionFilter( GetExceptionCode(),
+ 	                                 GetExceptionInformation(),
+@@ -5804,6 +5815,7 @@ static PyObject *PyApply(PyObject *self, PyObject *args)
+ 		Py_XDECREF(exc_value);
+ 		ret = NULL;
+ 	}
++#endif
+ 	return ret;
+ // @comm Calls the specified function in a manner similar to 
+ // the built-in function apply(), but allows Win32 exceptions
+diff --git a/win32/src/win32crypt/PyCRYPTPROV.cpp b/win32/src/win32crypt/PyCRYPTPROV.cpp
+index 140ddd3..3de895c 100644
+--- a/win32/src/win32crypt/PyCRYPTPROV.cpp
++++ b/win32/src/win32crypt/PyCRYPTPROV.cpp
+@@ -1,6 +1,10 @@
+ // @doc
+ #include "win32crypt.h"
+ 
++#if defined(__MINGW32__)
++#include <algorithm>
++#endif
++
+ // @object PyCRYPTPROV|Handle to a cryptographic provider, created using <om cryptoapi.CryptAcquireContext>
+ struct PyMethodDef PyCRYPTPROV::methods[] = {
+ 	// @pymeth CryptReleaseContext|Releases the CSP handle
+@@ -351,7 +355,11 @@ PyObject *PyCRYPTPROV::PyCryptGenRandom(PyObject *self, PyObject *args, PyObject
+ 	//initialize buffer with char string if passed if
+ 	ZeroMemory(pbBuffer, dwLen+1);
+ 	if (seeddata != NULL)
++#if defined(__MINGW32__)
++		memcpy(pbBuffer, seeddata, std::min(dwLen,seedlen));
++#else
+ 		memcpy(pbBuffer, seeddata, min(dwLen,seedlen));
++#endif
+ 	if (CryptGenRandom(hcryptprov, dwLen, pbBuffer))
+ 		ret=PyString_FromStringAndSize((char *)pbBuffer, dwLen);
+ 	else
+diff --git a/win32/src/win32crypt/win32cryptmodule.cpp b/win32/src/win32crypt/win32cryptmodule.cpp
+index 29b2c80..5875294 100644
+--- a/win32/src/win32crypt/win32cryptmodule.cpp
++++ b/win32/src/win32crypt/win32cryptmodule.cpp
+@@ -597,34 +597,59 @@ static PyObject *PyCertOpenStore(PyObject *self, PyObject *args, PyObject *kwarg
+ 		}
+ 	else{
+ 		switch((ULONG_PTR)StoreProvider){
++#if defined(__MINGW32__)
++			case (ULONG_PTR)14:
++			case (ULONG_PTR)8:
++			case (ULONG_PTR)10:
++			case (ULONG_PTR)13:
++			case (ULONG_PTR)16:{
++#else
+ 			case CERT_STORE_PROV_PHYSICAL:
+ 			case CERT_STORE_PROV_FILENAME:
+ 			case CERT_STORE_PROV_SYSTEM:
+ 			case CERT_STORE_PROV_SYSTEM_REGISTRY:
+ 			case CERT_STORE_PROV_LDAP:{
++#endif
+ 				if (!PyWinObject_AsWCHAR(obpvPara, (WCHAR **)&pvPara))
+ 					return NULL;
+ 				free_wchar=TRUE;
+ 				break;
+ 				}
++#if defined(__MINGW32__)
++			case (ULONG_PTR)4:{
++#else
+ 			case CERT_STORE_PROV_REG:{
++#endif
+ 				if (!PyWinObject_AsHKEY(obpvPara, (HKEY *)&pvPara))
+ 					return NULL;
+ 				break;
+ 				}
++#if defined(__MINGW32__)
++			case (ULONG_PTR)3:{
++#else
+ 			case CERT_STORE_PROV_FILE:{
++#endif
+ 				if (!PyWinObject_AsHANDLE(obpvPara, (HANDLE *)&pvPara))
+ 					return NULL;
+ 				break;
+ 				}
++#if defined(__MINGW32__)
++			case (ULONG_PTR)6:
++			case (ULONG_PTR)5:{
++#else
+ 			case CERT_STORE_PROV_SERIALIZED:
+ 			case CERT_STORE_PROV_PKCS7:{
++#endif
+ 				if (!PyWinObject_AsReadBuffer(obpvPara, (void **)&crypt_data_blob.pbData, &crypt_data_blob.cbData))
+ 					return NULL;
+ 				pvPara=(void *)&crypt_data_blob;
+ 				break;
+ 				}
++#if defined(__MINGW32__)
++			case (ULONG_PTR)2:{
++#else
+ 			case CERT_STORE_PROV_MEMORY:{
++#endif
+ 				// pvPara is not used, warn if something passed in
+ 				if (obpvPara != Py_None)
+ 					PyErr_Warn(PyExc_RuntimeWarning, "Para ignored for CERT_STORE_PROV_MEMORY");
+diff --git a/win32/src/win32evtlog.i b/win32/src/win32evtlog.i
+index 847230c..142923b 100644
+--- a/win32/src/win32evtlog.i
++++ b/win32/src/win32evtlog.i
+@@ -1012,11 +1012,15 @@ PyCFunction pfnPyEvtUpdateBookmark = (PyCFunction) PyEvtUpdateBookmark;
+ 
+ PyObject *PyWinObject_FromEVT_VARIANT(PEVT_VARIANT val)
+ {
++#if defined(__MINGW32__)
++	DWORD val_type = val->Type;
++#else
+ 	if (val->Type & EVT_VARIANT_TYPE_ARRAY){
+ 		PyErr_SetString(PyExc_NotImplementedError, "EVT_VARIANT arrays not supported yet");
+ 		return NULL;
+ 		}
+ 	DWORD val_type = val->Type & EVT_VARIANT_TYPE_MASK;
++#endif
+ 	PyObject *obval = NULL;
+ 	switch (val_type){
+ 		case EvtVarTypeNull:
+diff --git a/win32/src/win32file.i b/win32/src/win32file.i
+index 2b82d37..39e7cd1 100644
+--- a/win32/src/win32file.i
++++ b/win32/src/win32file.i
+@@ -1420,11 +1420,19 @@ static PyObject *PyObject_FromFILE_NOTIFY_INFORMATION(void *buffer, DWORD nbytes
+ 	// the filename is exactly 1 byte!  Not clear the best way to
+ 	// check this, but this works for now - is it at least the size of
+ 	// the *head* of the struct.
++#if defined(__MINGW32__)
++	if (nbytes < sizeof(DWORD)*3+2)
++#else
+ 	if (nbytes < sizeof DWORD*3+2)
++#endif
+ 		return ret;
+ 	DWORD nbytes_read = 0;
+ 	while (1) {
++#if defined(__MINGW32__)
++                PyObject *fname = PyWinObject_FromOLECHAR(p->FileName, p->FileNameLength/sizeof(WCHAR));
++#else
+ 		PyObject *fname = PyWinObject_FromOLECHAR(p->FileName, p->FileNameLength/sizeof WCHAR);
++#endif
+ 		if (!fname) {
+ 			Py_DECREF(ret);
+ 			return NULL;
+diff --git a/win32/src/win32file_comm.cpp b/win32/src/win32file_comm.cpp
+index 19f2eb7..d16fb76 100644
+--- a/win32/src/win32file_comm.cpp
++++ b/win32/src/win32file_comm.cpp
+@@ -173,11 +173,19 @@ PyDCB::~PyDCB(void)
+ {
+ }
+ 
++#if defined(__MINGW32__)
++#define GET_BITFIELD_ENTRY(bitfield_name) \
++	else if (strcmp(name, #bitfield_name)==0) { \
++		return PyInt_FromLong(pydcb->m_DCB. bitfield_name); \
++	} \
++
++#else
+ #define GET_BITFIELD_ENTRY(bitfield_name) \
+ 	else if (strcmp(name, #bitfield_name)==0) { \
+ 		return PyInt_FromLong(pydcb->m_DCB.##bitfield_name); \
+ 	} \
+ 
++#endif
+ PyObject *PyDCB::getattro(PyObject *self, PyObject *obname)
+ {
+ 	PyDCB *pydcb = (PyDCB *)self;
+@@ -204,7 +212,19 @@ PyObject *PyDCB::getattro(PyObject *self, PyObject *obname)
+ 	return PyObject_GenericGetAttr(self, obname);
+ }
+ 
++#if defined(__MINGW32__)
+ #define SET_BITFIELD_ENTRY(bitfield_name) \
++	else if (strcmp(name, #bitfield_name)==0) { \
++		if (!PyInt_Check(v)) { \
++			PyErr_Format(PyExc_TypeError, szNeedIntAttr, #bitfield_name); \
++			return -1; \
++		} \
++		pydcb->m_DCB. bitfield_name = PyInt_AsLong(v); \
++		return 0; \
++	} \
++
++#else
++#define SET_BITFIELD_ENTRY(bitfield_name)           \
+ 	else if (strcmp(name, #bitfield_name)==0) { \
+ 		if (!PyInt_Check(v)) { \
+ 			PyErr_Format(PyExc_TypeError, szNeedIntAttr, #bitfield_name); \
+@@ -214,6 +234,7 @@ PyObject *PyDCB::getattro(PyObject *self, PyObject *obname)
+ 		return 0; \
+ 	} \
+ 
++#endif
+ int PyDCB::setattro(PyObject *self, PyObject *obname, PyObject *v)
+ {
+ 	PyDCB *pydcb = (PyDCB *)self;
+@@ -367,11 +388,19 @@ PyCOMSTAT::~PyCOMSTAT(void)
+ }
+ 
+ #undef GET_BITFIELD_ENTRY
++#if defined(__MINGW32__)
++#define GET_BITFIELD_ENTRY(bitfield_name) \
++	else if (strcmp(name, #bitfield_name)==0) { \
++		return PyInt_FromLong(pyCOMSTAT->m_COMSTAT. bitfield_name); \
++	} \
++
++#else
+ #define GET_BITFIELD_ENTRY(bitfield_name) \
+ 	else if (strcmp(name, #bitfield_name)==0) { \
+ 		return PyInt_FromLong(pyCOMSTAT->m_COMSTAT.##bitfield_name); \
+ 	} \
+ 
++#endif
+ PyObject *PyCOMSTAT::getattro(PyObject *self, PyObject *obname)
+ {
+ 	PyCOMSTAT *pyCOMSTAT = (PyCOMSTAT *)self;
+@@ -392,6 +421,18 @@ PyObject *PyCOMSTAT::getattro(PyObject *self, PyObject *obname)
+ }
+ 
+ #undef SET_BITFIELD_ENTRY
++#if defined(__MINGW32__)
++#define SET_BITFIELD_ENTRY(bitfield_name) \
++	else if (strcmp(name, #bitfield_name)==0) { \
++		if (!PyInt_Check(v)) { \
++			PyErr_Format(PyExc_TypeError, szNeedIntAttr, #bitfield_name); \
++			return -1; \
++		} \
++		pyCOMSTAT->m_COMSTAT. bitfield_name = PyInt_AsLong(v); \
++		return 0; \
++	} \
++
++#else
+ #define SET_BITFIELD_ENTRY(bitfield_name) \
+ 	else if (strcmp(name, #bitfield_name)==0) { \
+ 		if (!PyInt_Check(v)) { \
+@@ -402,6 +443,7 @@ PyObject *PyCOMSTAT::getattro(PyObject *self, PyObject *obname)
+ 		return 0; \
+ 	} \
+ 
++#endif
+ int PyCOMSTAT::setattro(PyObject *self, PyObject *obname, PyObject *v)
+ {
+ 	PyCOMSTAT *pyCOMSTAT = (PyCOMSTAT *)self;
+diff --git a/win32/src/win32gui.i b/win32/src/win32gui.i
+index 94b738f..bc5e494 100644
+--- a/win32/src/win32gui.i
++++ b/win32/src/win32gui.i
+@@ -34,6 +34,9 @@
+ #include "Dbt.h" // device notification
+ #include "malloc.h"
+ 
++#if defined(__MINGW32__)
++#include <algorithm>
++#endif
+ #ifdef MS_WINCE
+ #include "winbase.h"
+ #define IS_INTRESOURCE(res) (((DWORD)(res) & 0xffff0000) == 0)
+@@ -640,7 +643,11 @@ typedef int UINT;
+ // @object TRACKMOUSEEVENT|A tuple of (dwFlags, hwndTrack, dwHoverTime)
+ %typemap(python,in) TRACKMOUSEEVENT *INPUT(TRACKMOUSEEVENT e){
+ 	PyObject *obhwnd;
++#if defined(__MINGW32__)
++	e.cbSize = sizeof(e);
++#else
+ 	e.cbSize = sizeof e;
++#endif
+ 	if (PyTuple_Check($source)) {
+ 		if (PyArg_ParseTuple($source, "lOl", &e.dwFlags, &obhwnd, &e.dwHoverTime) == 0) {
+ 			return PyErr_Format(PyExc_TypeError, "%s: a TRACKMOUSEEVENT must be a tuple of 3 integers", "$name");
+@@ -1822,7 +1829,11 @@ PyObject *PyFlashWindowEx(PyObject *self, PyObject *args)
+ 	PyObject *ret, *obhwnd;
+ 	BOOL rc;
+ 	FLASHWINFO f;
++#if defined(__MINGW32__)
++	f.cbSize = sizeof(f);
++#else
+ 	f.cbSize = sizeof f;
++#endif
+ 	// @pyparm <o PyHANDLE>|hwnd||Handle to a window
+ 	// @pyparm int|dwFlags||Combination of win32con.FLASHW_* flags
+ 	// @pyparm int|uCount||Nbr of times to flash
+@@ -3802,7 +3813,11 @@ static PyObject *PyExtractIconEx(PyObject *self, PyObject *args)
+     nicons_got = 1;
+ #endif
+     // Asking for 1 always says it got 2!?
++#if defined(__MINGW32__)
++    nicons = std::min(nicons, nicons_got);
++#else
+     nicons = min(nicons, nicons_got);
++#endif
+     objects_large = PyList_New(nicons);
+     if (!objects_large) goto done;
+     objects_small = PyList_New(nicons);
+@@ -4596,29 +4611,49 @@ BOOL GetOpenFileName(OPENFILENAME *INPUT);
+ %typemap (python, in) MENUITEMINFO *INPUT (Py_ssize_t target_size){
+ 	if (0 != PyObject_AsReadBuffer($source, (const void **)&$target, &target_size))
+ 		return NULL;
++#if defined(__MINGW32__)
++	if (sizeof(MENUITEMINFO) != target_size)
++		return PyErr_Format(PyExc_TypeError, "Argument must be a %d-byte string/buffer (got %d bytes)", sizeof(MENUITEMINFO), target_size);
++#else
+ 	if (sizeof MENUITEMINFO != target_size)
+ 		return PyErr_Format(PyExc_TypeError, "Argument must be a %d-byte string/buffer (got %d bytes)", sizeof MENUITEMINFO, target_size);
++#endif
+ }
+ 
+ %typemap (python,in) MENUITEMINFO *BOTH(Py_ssize_t target_size) {
+ 	if (0 != PyObject_AsWriteBuffer($source, (void **)&$target, &target_size))
+ 		return NULL;
++#if defined(__MINGW32__)
++	if (sizeof(MENUITEMINFO) != target_size)
++		return PyErr_Format(PyExc_TypeError, "Argument must be a %d-byte buffer (got %d bytes)", sizeof(MENUITEMINFO), target_size);
++#else
+ 	if (sizeof MENUITEMINFO != target_size)
+ 		return PyErr_Format(PyExc_TypeError, "Argument must be a %d-byte buffer (got %d bytes)", sizeof MENUITEMINFO, target_size);
++#endif
+ }
+ 
+ %typemap (python, in) MENUINFO *INPUT (Py_ssize_t target_size){
+ 	if (0 != PyObject_AsReadBuffer($source, (const void **)&$target, &target_size))
+ 		return NULL;
++#if defined(__MINGW32__)
++	if (sizeof(MENUINFO) != target_size)
++		return PyErr_Format(PyExc_TypeError, "Argument must be a %d-byte string/buffer (got %d bytes)", sizeof(MENUINFO), target_size);
++#else
+ 	if (sizeof MENUINFO != target_size)
+ 		return PyErr_Format(PyExc_TypeError, "Argument must be a %d-byte string/buffer (got %d bytes)", sizeof MENUINFO, target_size);
++#endif
+ }
+ 
+ %typemap (python,in) MENUINFO *BOTH(Py_ssize_t target_size) {
+ 	if (0 != PyObject_AsWriteBuffer($source, (void **)&$target, &target_size))
+ 		return NULL;
++#if defined(__MINGW32__)
++	if (sizeof(MENUINFO) != target_size)
++		return PyErr_Format(PyExc_TypeError, "Argument must be a %d-byte buffer (got %d bytes)", sizeof(MENUINFO), target_size);
++#else
+ 	if (sizeof MENUINFO != target_size)
+ 		return PyErr_Format(PyExc_TypeError, "Argument must be a %d-byte buffer (got %d bytes)", sizeof MENUINFO, target_size);
++#endif
+ }
+ 
+ // @pyswig |InsertMenuItem|Inserts a menu item
+@@ -4750,8 +4785,13 @@ PyObject *PySetMenuInfo(PyObject *self, PyObject *args)
+ 
+ 	if (0 != PyObject_AsReadBuffer(obInfo, (const void **)&pInfo, &cbInfo))
+ 		return NULL;
++#if defined(__MINGW32__)
++	if (sizeof(MENUINFO) != cbInfo)
++		return PyErr_Format(PyExc_TypeError, "Argument must be a %d byte string/buffer (got %d bytes)", sizeof(MENUINFO), cbInfo);
++#else
+ 	if (sizeof MENUINFO != cbInfo)
+ 		return PyErr_Format(PyExc_TypeError, "Argument must be a %d byte string/buffer (got %d bytes)", sizeof MENUINFO, cbInfo);
++#endif
+ 
+ 	Py_BEGIN_ALLOW_THREADS
+ 	result = (*pfnSetMenuInfo)(hmenu, pInfo);
+@@ -4787,8 +4827,13 @@ PyObject *PyGetMenuInfo(PyObject *self, PyObject *args)
+ 
+ 	if (0 != PyObject_AsWriteBuffer(obInfo, (void **)&pInfo, &cbInfo))
+ 		return NULL;
++#if defined(__MINGW32__)
++	if (sizeof(MENUINFO) != cbInfo)
++		return PyErr_Format(PyExc_TypeError, "Argument must be a %d byte buffer (got %d bytes)", sizeof(MENUINFO), cbInfo);
++#else
+ 	if (sizeof MENUINFO != cbInfo)
+ 		return PyErr_Format(PyExc_TypeError, "Argument must be a %d byte buffer (got %d bytes)", sizeof MENUINFO, cbInfo);
++#endif
+ 
+ 	Py_BEGIN_ALLOW_THREADS
+ 	result = (*pfnGetMenuInfo)(hmenu, pInfo);
+@@ -6005,7 +6050,11 @@ PyGetClassName(PyObject *self, PyObject *args)
+ 	if (!PyWinObject_AsHANDLE(obhwnd, (HANDLE *)&hwnd))
+ 		return NULL;
+ 	// dont bother with lock - no callback possible.
++#if defined(__MINGW32__)
++	int nchars = GetClassName(hwnd, buf, sizeof(buf)/sizeof(buf[0]));
++#else
+ 	int nchars = GetClassName(hwnd, buf, sizeof buf/sizeof buf[0]);
++#endif
+ 	if (nchars==0)
+ 		return PyWin_SetAPIError("GetClassName");
+ 	return PyWinObject_FromTCHAR(buf, nchars);
+@@ -6370,7 +6419,11 @@ BOOL PyParse_OPENFILENAMEW_Args(PyObject *args, PyObject *kwargs, OPENFILENAMEW
+ 	// lpstrFile buffer receives full path and possibly multiple file names, allocate extra space
+ 	if (!PyWinObject_AsWCHAR(obFile, &initfile, TRUE, &initfilechars))
+ 		goto done;
++#if defined(__MINGW32__)
++	pofn->nMaxFile=std::max(pofn->nMaxFile, initfilechars+1);
++#else
+ 	pofn->nMaxFile=max(pofn->nMaxFile, initfilechars+1);
++#endif
+ 	bufsize=pofn->nMaxFile*sizeof(WCHAR);
+ 	pofn->lpstrFile=(LPWSTR)malloc(bufsize);
+ 	if (pofn->lpstrFile==NULL){
+@@ -7506,13 +7559,13 @@ PyObject *PyRegisterDeviceNotification(PyObject *self, PyObject *args)
+ 				"structure says it has %d bytes, but %d was provided",
+ 				(int)struct_bytes, (int)nbytes);
+ 	// @pyseeapi RegisterDeviceNotification
+-	HDEVNOTIFY not;
++	HDEVNOTIFY notify;
+ 	Py_BEGIN_ALLOW_THREADS
+-	not = RegisterDeviceNotification(handle, (void *)filter, flags);
++	notify = RegisterDeviceNotification(handle, (void *)filter, flags);
+ 	Py_END_ALLOW_THREADS
+-	if (not == NULL)
++	if (notify == NULL)
+ 		return PyWin_SetAPIError("RegisterDeviceNotification");
+-	return PyWinObject_FromHDEVNOTIFY(not);
++	return PyWinObject_FromHDEVNOTIFY(notify);
+ }
+ %}
+ %native(RegisterDeviceNotification) PyRegisterDeviceNotification;
+diff --git a/win32/src/win32inet.i b/win32/src/win32inet.i
+index 92d7462..16a8912 100644
+--- a/win32/src/win32inet.i
++++ b/win32/src/win32inet.i
+@@ -15,6 +15,9 @@
+ %{
+ #undef PyHANDLE // undef earlier define, so we are back to the class.
+ #include "pywinobjects.h"
++#if defined(__MINGW32__)
++#include <algorithm>
++#endif
+ 
+ void CALLBACK PyHINTERNET_StatusChange(
+ 	HINTERNET hInternet,
+@@ -953,8 +956,10 @@ PyObject *PyInternetQueryOption(PyObject *self, PyObject *args)
+ 		case INTERNET_OPTION_RECEIVE_TIMEOUT:	// @flag INTERNET_OPTION_RECEIVE_TIMEOUT|Int - timeout in millseconds
+ 												// @flag INTERNET_OPTION_CONTROL_RECEIVE_TIMEOUT|Int - timeout in millseconds
+ 		case INTERNET_OPTION_CODEPAGE:		// @flag INTERNET_OPTION_CODEPAGE|Int - Codepage of host part of URL
++#if !defined(__MINGW32__)
+ 		case INTERNET_OPTION_CODEPAGE_PATH:	// @flag INTERNET_OPTION_CODEPAGE_PATH|Int - Codepage for URL
+ 		case INTERNET_OPTION_CODEPAGE_EXTRA:	// @flag INTERNET_OPTION_CODEPAGE_EXTRA|Int - Codepage for path part of URL
++#endif
+ 		case INTERNET_OPTION_CONNECT_RETRIES:		// @flag INTERNET_OPTION_CONNECT_RETRIES|Int - Number of time to try to reconnect to host
+ 		case INTERNET_OPTION_CONNECT_TIMEOUT:		// @flag INTERNET_OPTION_CONNECT_TIMEOUT|Int - Connection timeout in milliseconds
+ 		case INTERNET_OPTION_CONNECTED_STATE:		// @flag INTERNET_OPTION_CONNECTED_STATE|Int - Connection state, INTERNET_STATE_*
+@@ -962,7 +967,9 @@ PyObject *PyInternetQueryOption(PyObject *self, PyObject *args)
+ 		case INTERNET_OPTION_ERROR_MASK:		// @flag INTERNET_OPTION_ERROR_MASK|Int, combination of INTERNET_ERROR_MASK_*
+ 		case INTERNET_OPTION_EXTENDED_ERROR:		// @flag INTERNET_OPTION_EXTENDED_ERROR|Int, ERROR_INTERNET_*
+ 		case INTERNET_OPTION_FROM_CACHE_TIMEOUT:		// @flag INTERNET_OPTION_FROM_CACHE_TIMEOUT|Int - Timeout in ms before cached copy is used
++#if !defined(__MINGW32__)
+ 		case INTERNET_OPTION_IDN:		// @flag INTERNET_OPTION_IDN|Int, INTERNET_FLAG_IDN_*
++#endif
+ 		case INTERNET_OPTION_MAX_CONNS_PER_1_0_SERVER:		// @flag INTERNET_OPTION_MAX_CONNS_PER_1_0_SERVER|Int
+ 		case INTERNET_OPTION_MAX_CONNS_PER_SERVER:		// @flag INTERNET_OPTION_MAX_CONNS_PER_SERVER|Int
+ 		case INTERNET_OPTION_READ_BUFFER_SIZE:		// @flag INTERNET_OPTION_READ_BUFFER_SIZE|Int
+@@ -974,7 +981,9 @@ PyObject *PyInternetQueryOption(PyObject *self, PyObject *args)
+ 			ret=PyLong_FromUnsignedLong(*(unsigned long *)buf);
+ 			break;
+ 		case INTERNET_OPTION_BYPASS_EDITED_ENTRY:		// @flag INTERNET_OPTION_BYPASS_EDITED_ENTRY|Boolean
++#if !defined(__MINGW32__)
+ 		case INTERNET_OPTION_HTTP_DECODING:		// @flag INTERNET_OPTION_HTTP_DECODING|Boolean
++#endif
+ 		case INTERNET_OPTION_IGNORE_OFFLINE:		// @flag INTERNET_OPTION_IGNORE_OFFLINE|Boolean
+ 			ret=PyBool_FromLong(*(BOOL *)buf);
+ 			break;
+@@ -1157,14 +1166,18 @@ PyObject *PyInternetSetOption(PyObject *self, PyObject *args)
+ 		case INTERNET_OPTION_RECEIVE_TIMEOUT:	// @flag INTERNET_OPTION_RECEIVE_TIMEOUT|Int - timeout in millseconds
+ 												// @flag INTERNET_OPTION_CONTROL_RECEIVE_TIMEOUT|Int - timeout in millseconds
+ 		case INTERNET_OPTION_CODEPAGE:		// @flag INTERNET_OPTION_CODEPAGE|Int - Codepage of host part of URL
++#if !defined(__MINGW32__)
+ 		case INTERNET_OPTION_CODEPAGE_PATH:	// @flag INTERNET_OPTION_CODEPAGE_PATH|Codepage for URL
+ 		case INTERNET_OPTION_CODEPAGE_EXTRA:	// @flag INTERNET_OPTION_CODEPAGE_EXTRA|Int - Codepage for path part of URL
++#endif
+ 		case INTERNET_OPTION_CONNECT_RETRIES:		// @flag INTERNET_OPTION_CONNECT_RETRIES|Int - Number of time to try to reconnect to host
+ 		case INTERNET_OPTION_CONNECT_TIMEOUT:		// @flag INTERNET_OPTION_CONNECT_TIMEOUT|Int - Connection timeout in milliseconds
+ 		case INTERNET_OPTION_CONNECTED_STATE:		// @flag INTERNET_OPTION_CONNECTED_STATE|Int - Connection state, INTERNET_STATE_*
+ 		case INTERNET_OPTION_ERROR_MASK:		// @flag INTERNET_OPTION_ERROR_MASK|Int, combination of INTERNET_ERROR_MASK_*
+ 		case INTERNET_OPTION_FROM_CACHE_TIMEOUT:		// @flag INTERNET_OPTION_FROM_CACHE_TIMEOUT|Int - Timeout in ms before cached copy is used
++#if !defined(__MINGW32__)
+ 		case INTERNET_OPTION_IDN:		// @flag INTERNET_OPTION_IDN|Int, INTERNET_FLAG_IDN_*
++#endif
+ 		case INTERNET_OPTION_MAX_CONNS_PER_1_0_SERVER:		// @flag INTERNET_OPTION_MAX_CONNS_PER_1_0_SERVER|Int
+ 		case INTERNET_OPTION_MAX_CONNS_PER_SERVER:		// @flag INTERNET_OPTION_MAX_CONNS_PER_SERVER|Int
+ 		case INTERNET_OPTION_READ_BUFFER_SIZE:		// @flag INTERNET_OPTION_READ_BUFFER_SIZE|Int
+@@ -1189,7 +1202,9 @@ PyObject *PyInternetSetOption(PyObject *self, PyObject *args)
+ 				}
+ 			break;
+ 		case INTERNET_OPTION_BYPASS_EDITED_ENTRY:	// @flag INTERNET_OPTION_BYPASS_EDITED_ENTRY|Boolean
++#if !defined(__MINGW32__)
+ 		case INTERNET_OPTION_HTTP_DECODING:		// @flag INTERNET_OPTION_HTTP_DECODING|Boolean
++#endif
+ 		case INTERNET_OPTION_IGNORE_OFFLINE:	// @flag INTERNET_OPTION_IGNORE_OFFLINE|Boolean
+ 			bufsize=sizeof(BOOL);
+ 			buf=malloc(bufsize);
+@@ -1835,7 +1850,11 @@ BOOL PyWinObject_AsINTERNET_CACHE_GROUP_INFO(PyObject *ob, INTERNET_CACHE_GROUP_
+ 			}
+ 		}
+ 	if (bsuccess && GroupName)
++#if defined(__MINGW32__)
++		_tcsncpy(GroupInfo->szGroupName, GroupName, std::min(namelen, (DWORD)GROUPNAME_MAX_LENGTH));
++#else
+ 		_tcsncpy(GroupInfo->szGroupName, GroupName, min(namelen, GROUPNAME_MAX_LENGTH));
++#endif
+ 	Py_DECREF(dummy_tuple);
+ 	PyWinObject_FreeTCHAR(GroupName);
+ 	if (OwnerStorage)
+diff --git a/win32/src/win32net/win32net.h b/win32/src/win32net/win32net.h
+index ae7c690..c961c18 100644
+--- a/win32/src/win32net/win32net.h
++++ b/win32/src/win32net/win32net.h
+@@ -62,15 +62,27 @@ PyObject *PyDoGroupDelMembers(PyObject *self, PyObject *args);
+ 
+ #if WINVER >= 0x0500
+ typedef NET_API_STATUS (NET_API_FUNCTION *NetValidateNamefunc)(LPCWSTR, LPCWSTR, LPCWSTR, LPCWSTR, NETSETUP_NAME_TYPE);
+-extern NetValidateNamefunc pfnNetValidateName;
++extern
++#if defined(__MINGW32__)
++"C"
++#endif
++NetValidateNamefunc pfnNetValidateName;
+ 
+ typedef NET_API_STATUS (NET_API_FUNCTION *NetGetJoinInformationfunc)(LPCWSTR, LPWSTR *, PNETSETUP_JOIN_STATUS);
+ extern NetGetJoinInformationfunc pfnNetGetJoinInformation;
+ 
+ typedef NET_API_STATUS (NET_API_FUNCTION *NetValidatePasswordPolicyfunc)(LPCWSTR, LPVOID, NET_VALIDATE_PASSWORD_TYPE, LPVOID, LPVOID *);
+-extern NetValidatePasswordPolicyfunc pfnNetValidatePasswordPolicy;
++extern
++#if defined(__MINGW32__)
++"C"
++#endif
++NetValidatePasswordPolicyfunc pfnNetValidatePasswordPolicy;
+ 
+ typedef NET_API_STATUS (NET_API_FUNCTION *NetValidatePasswordPolicyFreefunc)(LPVOID *);
+-extern NetValidatePasswordPolicyFreefunc pfnNetValidatePasswordPolicyFree;
++extern
++#if defined(__MINGW32__)
++"C"
++#endif
++NetValidatePasswordPolicyFreefunc pfnNetValidatePasswordPolicyFree;
+ 
+ #endif // WINVER
+diff --git a/win32/src/win32pdhmodule.cpp b/win32/src/win32pdhmodule.cpp
+index 94c4ed1..533dad7 100644
+--- a/win32/src/win32pdhmodule.cpp
++++ b/win32/src/win32pdhmodule.cpp
+@@ -15,6 +15,10 @@ generates Windows .hlp files.
+ #include "pdh.h"
+ #include "pdhmsg.h"
+ 
++#if defined(__MINGW32__)
++#include <algorithm>
++#endif
++
+ /*
+ According to MSDN, Pdh calls are thread safe, although there was a bug
+ in Win2k that might make it appear to not be.  Plus, the PyW32* macros
+@@ -1013,12 +1017,21 @@ PDH_STATUS __stdcall PyCounterPathCallback(DWORD_PTR dwArg)
+ 	return rc;
+ }
+ 
++#if defined(__MINGW32__)
++#define SET_BOOL(r, i) { \
++	if (i<seqLen){ \
++		PyObject *subItem = PyTuple_GET_ITEM(flags_tuple, i); \
++		myCfg.cfg. r = PyObject_IsTrue(subItem); \
++	} \
++}
++#else
+ #define SET_BOOL(r, i) { \
+ 	if (i<seqLen){ \
+ 		PyObject *subItem = PyTuple_GET_ITEM(flags_tuple, i); \
+ 		myCfg.cfg.##r = PyObject_IsTrue(subItem); \
+ 	} \
+ }
++#endif
+ 
+ // @pymethod string|win32pdh|BrowseCounters|Displays the counter browsing dialog box so that the user can select the counters to be returned to the caller. 
+ static PyObject *PyBrowseCounters(PyObject *self, PyObject *args, PyObject *kwargs)
+@@ -1082,7 +1095,11 @@ static PyObject *PyBrowseCounters(PyObject *self, PyObject *args, PyObject *kwar
+ 	// Initialize the return buffer if starting path is passed in. (bInitializePath will also be set)
+ 	if (!PyWinObject_AsTCHAR(obInitialPath, &InitialPath, TRUE, &cchInitialPath))
+ 		return NULL;	// Last exit without cleanup
++#if defined(__MINGW32__)
++	myCfg.cfg.cchReturnPathLength = std::max(cchInitialPath+1, 1024UL);
++#else
+ 	myCfg.cfg.cchReturnPathLength = max(cchInitialPath+1, 1024);
++#endif
+ 	myCfg.cfg.szReturnPathBuffer = (TCHAR *)malloc(myCfg.cfg.cchReturnPathLength * sizeof(TCHAR));
+ 	if (myCfg.cfg.szReturnPathBuffer == NULL){
+ 		PyErr_NoMemory();
+diff --git a/win32/src/win32service.i b/win32/src/win32service.i
+index 11a4a23..fab8092 100644
+--- a/win32/src/win32service.i
++++ b/win32/src/win32service.i
+@@ -1818,7 +1818,6 @@ PyObject *PyQueryServiceConfig2(PyObject *self, PyObject *args)
+ #define SERVICE_CONTROL_HARDWAREPROFILECHANGE SERVICE_CONTROL_HARDWAREPROFILECHANGE
+ #define SERVICE_CONTROL_POWEREVENT SERVICE_CONTROL_POWEREVENT
+ #define SERVICE_CONTROL_SESSIONCHANGE SERVICE_CONTROL_SESSIONCHANGE
+-#define SERVICE_CONTROL_PRESHUTDOWN SERVICE_CONTROL_PRESHUTDOWN
+ 
+ 
+ #define SC_MANAGER_ALL_ACCESS SC_MANAGER_ALL_ACCESS 
+@@ -1875,7 +1874,6 @@ PyObject *PyQueryServiceConfig2(PyObject *self, PyObject *args)
+ #define SERVICE_ACCEPT_HARDWAREPROFILECHANGE SERVICE_ACCEPT_HARDWAREPROFILECHANGE
+ #define SERVICE_ACCEPT_POWEREVENT SERVICE_ACCEPT_POWEREVENT
+ #define SERVICE_ACCEPT_SESSIONCHANGE SERVICE_ACCEPT_SESSIONCHANGE
+-#define SERVICE_ACCEPT_PRESHUTDOWN SERVICE_ACCEPT_PRESHUTDOWN
+ 
+ //#define SERVICE_ERROR_IGNORER_IGNORE SERVICE_ERROR_IGNORER_IGNORE
+ #define SERVICE_BOOT_START SERVICE_BOOT_START 
+diff --git a/win32/src/win32trace.cpp b/win32/src/win32trace.cpp
+index 2237094..60e7c83 100644
+--- a/win32/src/win32trace.cpp
++++ b/win32/src/win32trace.cpp
+@@ -35,6 +35,9 @@ See - I told you the implementation was simple :-)
+ 
+ 
+ 
++#if defined(__MINGW32__)
++#include <algorithm>
++#endif
+ 
+ const unsigned long BUFFER_SIZE = 0x20000; // Includes size integer.
+ const TCHAR *MAP_OBJECT_NAME = _T("Global\\PythonTraceOutputMapping");
+@@ -341,7 +344,11 @@ BOOL PyTraceObject::WriteData(const char *data, unsigned len)
+     Py_BEGIN_ALLOW_THREADS
+     const char *data_this = data;
+     while (len) {
++#if defined(__MINGW32__)
++        unsigned len_this = std::min(static_cast<unsigned long>(len), BUFFER_SIZE/2);
++#else
+         unsigned len_this = min(len, BUFFER_SIZE/2);
++#endif
+         BOOL ok = GetMyMutex();
+         if (ok) {
+             // must use types with identical size on win32 and win64
Index: docker/msys/pywin32.patch
===================================================================
--- docker/msys/pywin32.patch	(revision 920)
+++ 	(revision )
@@ -1,2641 +1,0 @@
-diff --git a/com/win32com/src/ErrorUtils.cpp b/com/win32com/src/ErrorUtils.cpp
-index 1186cd1..314aff8 100644
---- a/com/win32com/src/ErrorUtils.cpp
-+++ b/com/win32com/src/ErrorUtils.cpp
-@@ -1118,9 +1118,15 @@ LPCTSTR GetScodeRangeString(HRESULT hr)
- 		HRESULT hrLast;
- 		LPCTSTR lpszName;
- 	};
-+#if defined(__MINGW32__)
-+	#define MAKE_RANGE_ENTRY(hrRange) \
-+                { static_cast<HRESULT>(hrRange##_FIRST), static_cast<HRESULT>(hrRange##_LAST), \
-+			_T(#hrRange) _T("_FIRST...") _T(#hrRange) _T("_LAST") }
-+#else
- 	#define MAKE_RANGE_ENTRY(hrRange) \
- 		{ hrRange##_FIRST, hrRange##_LAST, \
- 			_T(#hrRange) _T("_FIRST...") _T(#hrRange) _T("_LAST") }
-+#endif
- 
- 	static const RANGE_ENTRY hrRangeTable[] =
- 	{
-diff --git a/com/win32com/src/PyGatewayBase.cpp b/com/win32com/src/PyGatewayBase.cpp
-index fc091cb..2ed9acc 100644
---- a/com/win32com/src/PyGatewayBase.cpp
-+++ b/com/win32com/src/PyGatewayBase.cpp
-@@ -7,6 +7,10 @@
- 
- #include "PythonCOMServer.h"
- 
-+#if defined(__MINGW32__)
-+#include <algorithm>
-+#endif
-+
- // {25D29CD0-9B98-11d0-AE79-4CF1CF000000}
- extern const GUID IID_IInternalUnwrapPythonObject = 
- 	{ 0x25d29cd0, 0x9b98, 0x11d0, { 0xae, 0x79, 0x4c, 0xf1, 0xcf, 0x0, 0x0, 0x0 } };
-@@ -437,7 +441,11 @@ static HRESULT invoke_setup(
- 		// make sure its not a special DISPID we don't understand.
- 		if (params->rgdispidNamedArgs[i] < 0)
- 			return DISP_E_PARAMNOTFOUND;
-+#if defined(__MINGW32__)
-+		numArgs = std::max(numArgs, (UINT)params->rgdispidNamedArgs[i]+1);
-+#else
- 		numArgs = max(numArgs, (UINT)params->rgdispidNamedArgs[i]+1);
-+#endif
- 	}
- 
- 	PyObject *argList = PyTuple_New(numArgs);
-@@ -658,7 +666,11 @@ static HRESULT invoke_finish(
- 			ob = NULL;
- 			firstByRef = 1;
- 		}
-+#if defined(__MINGW32__)
-+		UINT max_args = std::min(cUserResult-firstByRef, pDispParams->cArgs);
-+#else
- 		UINT max_args = min(cUserResult-firstByRef, pDispParams->cArgs);
-+#endif
- 		UINT *offsets = (UINT *)_malloca(sizeof(UINT) * max_args);
- 		// Get the offsets into our params of all BYREF args, in order.
- 		fill_byref_offsets(pDispParams, offsets, max_args);
-diff --git a/com/win32com/src/PythonCOM.cpp b/com/win32com/src/PythonCOM.cpp
-index da00839..67983a4 100644
---- a/com/win32com/src/PythonCOM.cpp
-+++ b/com/win32com/src/PythonCOM.cpp
-@@ -342,11 +342,13 @@ static PyObject *pythoncom_CoInitializeSecurity(PyObject *self, PyObject *args)
- 			pSD = (PSECURITY_DESCRIPTOR)&appid;
- 			}
- 		}
-+#if !defined(__MINGW32__)
- 	else if (dwCapabilities & EOAC_ACCESS_CONTROL){
- 		if (!PyCom_InterfaceFromPyObject(obSD, IID_IAccessControl, (void **)&pIAC, FALSE))
- 			return NULL;
- 		pSD = (PSECURITY_DESCRIPTOR)pIAC;
- 		}
-+#endif
- 	else{
- 		if (!PyWinObject_AsSECURITY_DESCRIPTOR(obSD, &pSD, /*BOOL bNoneOK = */TRUE))
- 			return NULL;
-diff --git a/com/win32com/src/PythonCOM.def b/com/win32com/src/PythonCOM.def
-index 58d030f..6d2a54b 100644
---- a/com/win32com/src/PythonCOM.def
-+++ b/com/win32com/src/PythonCOM.def
-@@ -1,15 +1,15 @@
- EXPORTS
--	DllCanUnloadNow     @1 PRIVATE
--	DllGetClassObject   @2 PRIVATE
-+	DllCanUnloadNow
-+	DllGetClassObject
- 
- 	; Some exports for clients who may "LoadLibrary"...
--	PyCom_VariantFromPyObject
--	PyCom_PyObjectFromVariant
--	PyCom_InterfaceFromPyObject
--	PyCom_PyObjectFromIUnknown
--	PyCom_MakeOlePythonCall
-+	_PyCom_VariantFromPyObject
-+	_PyCom_PyObjectFromVariant
-+	_PyCom_InterfaceFromPyObject
-+	_PyCom_PyObjectFromIUnknown
-+	_PyCom_MakeOlePythonCall
- 
--	PyCom_CoInitializeEx
--	PyCom_CoInitialize
--	PyCom_CoUninitialize
-+	_PyCom_CoInitializeEx
-+	_PyCom_CoInitialize
-+	_PyCom_CoUninitialize
- 
-diff --git a/com/win32com/src/Register.cpp b/com/win32com/src/Register.cpp
-index 0b24ee2..d259aff 100644
---- a/com/win32com/src/Register.cpp
-+++ b/com/win32com/src/Register.cpp
-@@ -322,7 +322,9 @@ static const PyCom_InterfaceSupportInfo g_interfaceSupportData[] =
- 	PYCOM_INTERFACE_FULL	   ( CancelMethodCalls),
- 	// No wrapper for IAccessControl yet, but you can still get the system implementation
- 	//  by calling pythoncom.CoCreateInstance with IID_IUnknown as the returned interface
-+#if !defined(__MINGW32__)
- 	PYCOM_INTERFACE_CLSID_ONLY (DCOMAccessControl),
-+#endif
- 
- 	// NULL, Unknown and dispatch special cases.
- 	{ &IID_NULL, "Null", "IID_NULL", NULL, NULL},
-diff --git a/com/win32com/src/dllmain.cpp b/com/win32com/src/dllmain.cpp
-index fb81ddb..abf074c 100644
---- a/com/win32com/src/dllmain.cpp
-+++ b/com/win32com/src/dllmain.cpp
-@@ -175,6 +175,9 @@ typedef HRESULT (WINAPI *PFNCoInitializeEx)(LPVOID pvReserved, DWORD dwCoInit);
- // the Init for Term function explicitely, and the framework will detect
- // it no longer needs doing.
- // XXX - Needs more thought about threading implications.
-+#if defined(__MINGW32__)
-+extern "C"
-+#endif
- HRESULT PyCom_CoInitializeEx(LPVOID reserved, DWORD dwInit)
- {
- 	// Must be thread-safe, although doesnt need the Python lock.
-diff --git a/com/win32com/src/include/PythonCOM.h b/com/win32com/src/include/PythonCOM.h
-index 9e422e4..f3b1063 100644
---- a/com/win32com/src/include/PythonCOM.h
-+++ b/com/win32com/src/include/PythonCOM.h
-@@ -111,10 +111,8 @@
- #ifdef __MINGW32__
- // Special Mingw32 considerations.
- #define NO_PYCOM_IDISPATCHEX
--#define NO_PYCOM_IPROVIDECLASSINFO
- #define NO_PYCOM_ISERVICEPROVIDER
- #define NO_PYCOM_ENUMSTATPROPSTG
--#define NO_PYCOM_IPROPERTYSTORAGE
- #define __try try
- #define __except catch
- #include <olectl.h>
-@@ -305,6 +303,9 @@ PYCOM_EXPORT PyObject *PyObject_FromOLEMENUGROUPWIDTHS(const OLEMENUGROUPWIDTHS
- 
- /* Functions for Initializing COM, and also letting the core know about it!
- */
-+#if defined(__MINGW32__)
-+extern "C"
-+#endif
- PYCOM_EXPORT HRESULT PyCom_CoInitializeEx(LPVOID reserved, DWORD dwInit);
- PYCOM_EXPORT HRESULT PyCom_CoInitialize(LPVOID reserved);
- PYCOM_EXPORT void PyCom_CoUninitialize();
-diff --git a/com/win32com/src/initguid.cpp b/com/win32com/src/initguid.cpp
-new file mode 100644
-index 0000000..33d5923
---- /dev/null
-+++ b/com/win32com/src/initguid.cpp
-@@ -0,0 +1,7 @@
-+#define INITGUID
-+#undef _OBJIDLBASE_
-+#define CINTERFACE
-+#define USE_COM_CONTEXT_DEF
-+#include <objidl.h>
-+#include <ksguid.h>
-+#include <ks.h>
-diff --git a/com/win32comext/axcontrol/src/PyIOleCommandTarget.cpp b/com/win32comext/axcontrol/src/PyIOleCommandTarget.cpp
-index 61bd706..e7908e9 100644
---- a/com/win32comext/axcontrol/src/PyIOleCommandTarget.cpp
-+++ b/com/win32comext/axcontrol/src/PyIOleCommandTarget.cpp
-@@ -4,6 +4,10 @@
- #include "axcontrol_pch.h"
- #include "PyIOleCommandTarget.h"
- 
-+#if defined(__MINGW32__)
-+#include <algorithm>
-+#endif
-+
- static BOOL FillOLECMDsWithSequence(OLECMD *pCmds, UINT ncmds, PyObject *obCmds)
- {
- 	for (UINT i=0;i<ncmds;i++) {
-@@ -211,7 +215,11 @@ STDMETHODIMP PyGOleCommandTarget::QueryStatus(
- 			ok = PyWinObject_AsAutoFreeBstr(obText, &tempString);
- 			if (ok) {
- 				UINT strLen = SysStringLen(tempString);
-+#if defined(__MINGW32__)
-+				UINT nwrite = std::min((ULONG)strLen, pCmdText->cwBuf);
-+#else
- 				UINT nwrite = min(strLen, pCmdText->cwBuf);
-+#endif
- 				wcsncpy(pCmdText->rgwz, (WCHAR *)(BSTR)tempString,
- 					nwrite);
- 				pCmdText->cwActual = nwrite;
-diff --git a/com/win32comext/axcontrol/src/initguid.cpp b/com/win32comext/axcontrol/src/initguid.cpp
-new file mode 100644
-index 0000000..329e211
---- /dev/null
-+++ b/com/win32comext/axcontrol/src/initguid.cpp
-@@ -0,0 +1,8 @@
-+#define INITGUID
-+#undef _OBJIDLBASE_
-+#define CINTERFACE
-+#define USE_COM_CONTEXT_DEF
-+#include <objidl.h>
-+#include <ksguid.h>
-+#include <ks.h>
-+#include <docobj.h>
-diff --git a/com/win32comext/axscript/src/initguid.cpp b/com/win32comext/axscript/src/initguid.cpp
-new file mode 100644
-index 0000000..ba6baa3
---- /dev/null
-+++ b/com/win32comext/axscript/src/initguid.cpp
-@@ -0,0 +1,8 @@
-+#define INITGUID
-+#undef _OBJIDLBASE_
-+#define CINTERFACE
-+#define USE_COM_CONTEXT_DEF
-+#include <objidl.h>
-+#include <ksguid.h>
-+#include <ks.h>
-+#include <objsafe.h>
-diff --git a/com/win32comext/internet/src/PyIInternetProtocol.cpp b/com/win32comext/internet/src/PyIInternetProtocol.cpp
-index 43c25a8..b910c85 100644
---- a/com/win32comext/internet/src/PyIInternetProtocol.cpp
-+++ b/com/win32comext/internet/src/PyIInternetProtocol.cpp
-@@ -5,6 +5,10 @@
- #include "PyIInternetProtocolRoot.h"
- #include "PyIInternetProtocol.h"
- 
-+#if defined(__MINGW32__)
-+#include <algorithm>
-+#endif
-+
- // @doc - This file contains autoduck documentation
- // ---------------------------------------------------
- //
-@@ -181,7 +185,11 @@ STDMETHODIMP PyGInternetProtocol::Read(
- 		hr = PyCom_HandlePythonFailureToCOM();
- 	} else {
- 		char *buf = PyString_AsString(result);
-+#if defined(__MINGW32__)
-+		*pcbRead = std::min(cb, (ULONG)PyString_Size(result));
-+#else
- 		*pcbRead = min(cb, (ULONG)PyString_Size(result));
-+#endif
- 		memcpy( pv, buf, *pcbRead);
- 	}
- 	return hr;
-diff --git a/com/win32comext/internet/src/PyIInternetProtocolInfo.cpp b/com/win32comext/internet/src/PyIInternetProtocolInfo.cpp
-index c00e43e..ef894ca 100644
---- a/com/win32comext/internet/src/PyIInternetProtocolInfo.cpp
-+++ b/com/win32comext/internet/src/PyIInternetProtocolInfo.cpp
-@@ -4,6 +4,10 @@
- #include "internet_pch.h"
- #include "PyIInternetProtocolInfo.h"
- 
-+#if defined(__MINGW32__)
-+#include <algorithm>
-+#endif
-+
- // @doc - This file contains autoduck documentation
- // ---------------------------------------------------
- //
-@@ -226,7 +230,11 @@ STDMETHODIMP PyGInternetProtocolInfo::ParseUrl(
- 	if (!PyWinObject_AsBstr(result, &bstrTemp, FALSE, pcchResult)) bPythonIsHappy = FALSE;
- 	if (!bPythonIsHappy) return PyCom_HandlePythonFailureToCOM(/*pexcepinfo*/);
- 	++(*pcchResult); // Null terminator
-+#if defined(__MINGW32__)
-+	*pcchResult = std::min(*pcchResult, cchResult);
-+#else
- 	*pcchResult = min(*pcchResult, cchResult);
-+#endif
- 	memcpy(pwzResult, bstrTemp, *pcchResult * sizeof(WCHAR));
- 	SysFreeString(bstrTemp);
- 	Py_DECREF(result);
-@@ -258,7 +266,11 @@ STDMETHODIMP PyGInternetProtocolInfo::CombineUrl(
- 	if (!PyWinObject_AsBstr(result, &bstrTemp, FALSE, pcchResult)) bPythonIsHappy = FALSE;
- 	if (!bPythonIsHappy) hr = PyCom_HandlePythonFailureToCOM(/*pexcepinfo*/);
- 	++(*pcchResult); // Null terminator
-+#if defined(__MINGW32__)
-+	*pcchResult = std::min(*pcchResult, cchResult);
-+#else
- 	*pcchResult = min(*pcchResult, cchResult);
-+#endif
- 	memcpy(pwzResult, bstrTemp, *pcchResult * sizeof(WCHAR));
- 	SysFreeString(bstrTemp);
- 	Py_DECREF(result);
-@@ -312,7 +324,11 @@ STDMETHODIMP PyGInternetProtocolInfo::QueryInfo(
- 			return PyCom_HandlePythonFailureToCOM();
- 		}
- 	} else {
-+#if defined(__MINGW32__)
-+		*pcbBuf = std::min(cbBuffer, (ULONG)PyString_Size(result));
-+#else
- 		*pcbBuf = min(cbBuffer, (ULONG)PyString_Size(result));
-+#endif
- 		memcpy(pBuffer, PyString_AsString(result), *pcbBuf);
- 	}
- 	Py_DECREF(result);
-diff --git a/com/win32comext/internet/src/PyIInternetSecurityManager.cpp b/com/win32comext/internet/src/PyIInternetSecurityManager.cpp
-index 81439fc..a4cb106 100644
---- a/com/win32comext/internet/src/PyIInternetSecurityManager.cpp
-+++ b/com/win32comext/internet/src/PyIInternetSecurityManager.cpp
-@@ -4,6 +4,10 @@
- #include "internet_pch.h"
- #include "PyIInternetSecurityManager.h"
- 
-+#if defined(__MINGW32__)
-+#include <algorithm>
-+#endif
-+
- // @doc - This file contains autoduck documentation
- // ---------------------------------------------------
- //
-@@ -338,7 +342,11 @@ STDMETHODIMP PyGInternetSecurityManager::GetSecurityId(
- 		Py_DECREF(result);
- 		return MAKE_PYCOM_GATEWAY_FAILURE_CODE("GetSecurityId");
- 	}
-+#if defined(__MINGW32__)
-+	*pcbSecurityId = std::min(buf_len, *pcbSecurityId);
-+#else
- 	*pcbSecurityId = min(buf_len, *pcbSecurityId);
-+#endif
- 	memcpy(pbSecurityId, buf, *pcbSecurityId);
- 	Py_DECREF(result);
- 	return hr;
-diff --git a/com/win32comext/internet/src/initguid.cpp b/com/win32comext/internet/src/initguid.cpp
-new file mode 100644
-index 0000000..1003585
---- /dev/null
-+++ b/com/win32comext/internet/src/initguid.cpp
-@@ -0,0 +1,9 @@
-+#define INITGUID
-+#undef _OBJIDLBASE_
-+#define CINTERFACE
-+#define USE_COM_CONTEXT_DEF
-+#include <objidl.h>
-+#include <ksguid.h>
-+#include <ks.h>
-+#include <urlmon.h>
-+#include <mshtmhst.h>
-diff --git a/com/win32comext/propsys/src/PyPROPVARIANT.cpp b/com/win32comext/propsys/src/PyPROPVARIANT.cpp
-index b330129..694703f 100644
---- a/com/win32comext/propsys/src/PyPROPVARIANT.cpp
-+++ b/com/win32comext/propsys/src/PyPROPVARIANT.cpp
-@@ -3,7 +3,13 @@
- 
- #include "PythonCOM.h"
- #include "PyPROPVARIANT.h"
-+#if defined(__MINGW32__)
-+extern "C" {
-+#endif
- #include "propvarutil.h"
-+#if defined(__MINGW32__)
-+}
-+#endif
- #include "float.h"
- 
- // @doc - This file contains autoduck documentation
-diff --git a/com/win32comext/propsys/src/propsys.cpp b/com/win32comext/propsys/src/propsys.cpp
-index ef0a2f4..69ff21f 100644
---- a/com/win32comext/propsys/src/propsys.cpp
-+++ b/com/win32comext/propsys/src/propsys.cpp
-@@ -279,6 +279,7 @@ static PyObject *PyPSGetItemPropertyHandler(PyObject *self, PyObject *args)
- 	return PyCom_PyObjectFromIUnknown((IUnknown *)propertystore, riid, FALSE);
- }
- 
-+#if !defined(__MINGW32__)
- // @pymethod bytes|propsys|StgSerializePropVariant|Serializes a <o PyPROPVARIANT>
- static PyObject *PyStgSerializePropVariant(PyObject *self, PyObject *args)
- {
-@@ -319,6 +320,7 @@ static PyObject *PyStgDeserializePropVariant(PyObject *self, PyObject *args)
- 		return PyCom_BuildPyException(hr);
- 	return PyWinObject_FromPROPVARIANT(&pv);
- };
-+#endif
- 
- // @pymethod <o PyIPropertyStore>|propsys|PSCreateMemoryPropertyStore|Creates a temporary property store that is not connected to any backing storage
- // @comm May also be used to create <o PyINamedPropertyStore>, <o PyIPropertyStoreCache>, <o PyIPersistStream>, or <o PyIPropertyBag>
-@@ -566,8 +568,10 @@ static struct PyMethodDef propsys_methods[]=
- 	{ "PSRegisterPropertySchema", PyPSRegisterPropertySchema, 1 }, // @pymeth PSRegisterPropertySchema|Registers a group of properties described in a schema file
- 	{ "PSUnregisterPropertySchema", PyPSUnregisterPropertySchema, 1 }, // @pymeth PSUnregisterPropertySchema|Removes a property schema definition
- 	{ "SHGetPropertyStoreFromParsingName", PySHGetPropertyStoreFromParsingName, 1 }, // @pymeth SHGetPropertyStoreFromParsingName|Retrieves the property store for an item by path
-+#if !defined(__MINGW32__)
- 	{ "StgSerializePropVariant", PyStgSerializePropVariant, 1 }, // @pymeth StgSerializePropVariant|Serializes a <o PyPROPVARIANT>
- 	{ "StgDeserializePropVariant", PyStgDeserializePropVariant, 1 }, // @pymeth StgDeserializePropVariant|Creates a <o PyPROPVARIANT> from a serialized buffer
-+#endif
- 	{ "PSCreateMemoryPropertyStore", PyPSCreateMemoryPropertyStore, 1 }, // @pymeth PSCreateMemoryPropertyStore|Creates a temporary property store that is not connected to any backing storage
- 	{ "PSCreatePropertyStoreFromPropertySetStorage", PyPSCreatePropertyStoreFromPropertySetStorage, 1 }, // @pymeth PSCreatePropertyStoreFromPropertySetStorage|Wraps a <o PyIPropertySetStorage> interface in a <o PyIPropertyStore> object
- 	{ "PSLookupPropertyHandlerCLSID", PyPSLookupPropertyHandlerCLSID, 1 }, // @pymeth PSLookupPropertyHandlerCLSID|Returns the GUID of the property handler for a file
-@@ -583,7 +587,7 @@ static struct PyMethodDef propsys_methods[]=
- 	// MSDN says CLSID_PropertyChangeArray can be used to create IPropertyChangeArray, but
- 	// I get "Class not registered".  Plus, it doesn't appear in any headers, although
- 	// it's contained in uuid.lib.
--#ifndef CLSID_PropertyChangeArray
-+#if !defined(CLSID_PropertyChangeArray) && !defined(__MINGW32__)
- 	EXTERN_C const CLSID CLSID_PropertyChangeArray;
- #endif
- 
-@@ -606,7 +610,9 @@ static const PyCom_InterfaceSupportInfo g_interfaceSupportData[] =
- 	PYCOM_INTERFACE_CLIENT_ONLY (ObjectWithPropertyKey),
- 	PYCOM_INTERFACE_CLIENT_ONLY (PropertyChange),
- 	PYCOM_INTERFACE_CLIENT_ONLY (PropertyChangeArray),
-+#if !defined(__MINGW32__)
- 	PYCOM_INTERFACE_CLSID_ONLY (PropertyChangeArray),
-+#endif
- };
- 
- /* Module initialisation */
-diff --git a/com/win32comext/shell/src/PyICategoryProvider.cpp b/com/win32comext/shell/src/PyICategoryProvider.cpp
-index e2f2ea8..0ecf0cf 100644
---- a/com/win32comext/shell/src/PyICategoryProvider.cpp
-+++ b/com/win32comext/shell/src/PyICategoryProvider.cpp
-@@ -9,6 +9,10 @@
- //
- // Interface Implementation
- 
-+#if defined(__MINGW32__)
-+__CRT_UUID_DECL(int, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
-+#endif
-+
- PyICategoryProvider::PyICategoryProvider(IUnknown *pdisp):
- 	PyIUnknown(pdisp)
- {
-diff --git a/com/win32comext/shell/src/initguid.cpp b/com/win32comext/shell/src/initguid.cpp
-new file mode 100644
-index 0000000..8da5c87
---- /dev/null
-+++ b/com/win32comext/shell/src/initguid.cpp
-@@ -0,0 +1,11 @@
-+#define INITGUID
-+#undef _OBJIDLBASE_
-+#define CINTERFACE
-+#define USE_COM_CONTEXT_DEF
-+#include <objidl.h>
-+#include <ksguid.h>
-+#include <ks.h>
-+#include <shlguid.h>
-+#include <shobjidl.h>
-+#include <emptyvc.h>
-+#include <_mingw.h>
-diff --git a/com/win32comext/shell/src/shell.cpp b/com/win32comext/shell/src/shell.cpp
-index 8b6e78c..f19a021 100644
---- a/com/win32comext/shell/src/shell.cpp
-+++ b/com/win32comext/shell/src/shell.cpp
-@@ -29,8 +29,10 @@ generates Windows .hlp files.
- #include "PyIShellExtInit.h"
- #include "PyIShellFolder.h"
- #include "PyIShellFolder2.h"
-+#if !defined(__MINGW32__)
- #include "PyIEmptyVolumeCache.h"
- #include "PyIEmptyVolumeCacheCallBack.h"
-+#endif
- #include "PyIEnumExplorerCommand.h"
- #include "PyIEnumIDList.h"
- #include "PyICopyHook.h"
-@@ -3606,12 +3608,16 @@ static const PyCom_InterfaceSupportInfo g_interfaceSupportData[] =
- 	PYCOM_INTERFACE_FULL(ColumnProvider),
- 	PYCOM_INTERFACE_CLIENT_ONLY(DefaultExtractIconInit),
- 	PYCOM_INTERFACE_FULL(DropTargetHelper),
-+#if !defined(__MINGW32__)
- 	PYCOM_INTERFACE_CLIENT_ONLY(EmptyVolumeCacheCallBack),
-+#endif
- 	PYCOM_INTERFACE_CLIENT_ONLY(QueryAssociations),
- 	PYCOM_INTERFACE_SERVER_ONLY(DeskBand),
- 	PYCOM_INTERFACE_SERVER_ONLY(DockingWindow),
-+#if !defined(__MINGW32__)
- 	PYCOM_INTERFACE_SERVER_ONLY(EmptyVolumeCache),
- 	PYCOM_INTERFACE_SERVER_ONLY(EmptyVolumeCache2),
-+#endif
- 	PYCOM_INTERFACE_CLIENT_ONLY(ExplorerBrowser),
- 	PYCOM_INTERFACE_FULL(ExplorerBrowserEvents),
- 	PYCOM_INTERFACE_FULL(ExplorerCommand),
-@@ -3850,12 +3856,16 @@ PYWIN_MODULE_INIT_FUNC(shell)
- 	ADD_IID(FMTID_Briefcase);
- 	ADD_IID(FMTID_Misc);
- 	ADD_IID(FMTID_WebView);
-+#if !defined(__MINGW32__)
- 	ADD_IID(FMTID_AudioSummaryInformation);
-+#endif
- 	ADD_IID(FMTID_Volume);
- 	ADD_IID(FMTID_Query);
-+#if !defined(__MINGW32__)
- 	ADD_IID(FMTID_SummaryInformation);
- 	ADD_IID(FMTID_MediaFileSummaryInformation);
- 	ADD_IID(FMTID_ImageSummaryInformation);
-+#endif
- 	ADD_IID(IID_CDefView);
- 
- 	ADD_IID(EP_NavPane);
-diff --git a/com/win32comext/taskscheduler/src/initguid.cpp b/com/win32comext/taskscheduler/src/initguid.cpp
-new file mode 100644
-index 0000000..d588502
---- /dev/null
-+++ b/com/win32comext/taskscheduler/src/initguid.cpp
-@@ -0,0 +1,8 @@
-+#define INITGUID
-+#undef _OBJIDLBASE_
-+#define CINTERFACE
-+#define USE_COM_CONTEXT_DEF
-+#include <objidl.h>
-+#include <ksguid.h>
-+#include <ks.h>
-+#include <mstask.h>
-diff --git a/isapi/src/Utils.cpp b/isapi/src/Utils.cpp
-index 8f278f2..b8976ae 100644
---- a/isapi/src/Utils.cpp
-+++ b/isapi/src/Utils.cpp
-@@ -127,7 +127,11 @@ static void CheckRegisterEventSourceFile()
- 		return;
- 
- 	GetModuleFileNameW(g_hInstance, mod_name,
-+#if defined(__MINGW32__)
-+			  sizeof(mod_name)/sizeof(WCHAR));
-+#else
- 			  sizeof mod_name/sizeof WCHAR);
-+#endif
- 	if (!mod_name[0]) {
- 		OutputDebugString(_T("GetModuleFileNameW failed!"));
- 		return;
-@@ -160,6 +164,9 @@ static void CheckRegisterEventSourceFile()
- }
- 
- // Write stuff to the event log.
-+#if defined(__MINGW32__)
-+extern "C"
-+#endif
- BOOL WriteEventLogMessage(WORD eventType, DWORD eventID, WORD num_inserts,
-                           const char **inserts)
- {
-diff --git a/isapi/src/Utils.h b/isapi/src/Utils.h
-index 3779ca9..f076826 100644
---- a/isapi/src/Utils.h
-+++ b/isapi/src/Utils.h
-@@ -58,6 +58,9 @@ char *HTMLErrorResp(const char *msg);
- TCHAR *GetModulePath(void);
- 
- // Write entry to the event log
-+#if defined(__MINGW32__)
-+extern "C"
-+#endif
- BOOL WriteEventLogMessage(WORD eventType, DWORD eventID, WORD num_inserts,
-                           const char **inserts);
- 
-diff --git a/isapi/src/pyISAPI.cpp b/isapi/src/pyISAPI.cpp
-index 439d3ca..2c94610 100644
---- a/isapi/src/pyISAPI.cpp
-+++ b/isapi/src/pyISAPI.cpp
-@@ -52,6 +52,9 @@ char g_CallbackModuleName[_MAX_PATH + _MAX_FNAME] = "";
- #define TRACE(x) OutputDebugString(_T(x))
- 
- // This is an entry point for py2exe.
-+#if defined(__MINGW32__)
-+extern "C"
-+#endif
- void WINAPI PyISAPISetOptions(const char *modname, BOOL is_frozen)
- {
- 	strncpy(g_CallbackModuleName, modname,
-diff --git a/setup.py b/setup.py
-index 7c35d90..5872968 100644
---- a/setup.py
-+++ b/setup.py
-@@ -72,6 +72,8 @@ import shutil
- 
- is_py3k = sys.version_info > (3,) # get this out of the way early on...
- 
-+build_mingw32=True
-+
- try:
-     import winreg # py3k
- except ImportError:
-@@ -140,6 +142,10 @@ dll_base_address = 0x1e200000
- def find_platform_sdk_dir():
-     # The user might have their current environment setup for the
-     # SDK, in which case "MSSDK_INCLUDE" and "MSSDK_LIB" vars must be set.
-+    if build_mingw32:
-+        return { "include": ["c:/msys64/mingw32/include", "c:/msys64/mingw32/i686-w64-mingw32/include"], 
-+	         "lib": ["c:/msys64/mingw32/lib", "c:/msys64//mingw32/i686-w64-mingw32/lib"] }
-+
-     if "MSSDK_INCLUDE" in os.environ and "MSSDK_LIB" in os.environ:
-         print("Using SDK as specified in the environment")
-         return {
-@@ -173,9 +179,10 @@ def find_platform_sdk_dir():
- # to prevent the extension from loading.  For more details, see
- # http://bugs.python.org/issue7833 (which has landed for Python 2.7 and on 3.2
- # and later, which are all we care about currently)
--from distutils.msvc9compiler import MSVCCompiler
--MSVCCompiler._orig_spawn = MSVCCompiler.spawn
--MSVCCompiler._orig_link = MSVCCompiler.link
-+if not build_mingw32:
-+    from distutils.msvc9compiler import MSVCCompiler
-+    MSVCCompiler._orig_spawn = MSVCCompiler.spawn
-+    MSVCCompiler._orig_link = MSVCCompiler.link
- 
- # We need to override this method for versions where issue7833 *has* landed
- # (ie, 2.7 and 3.2+)
-@@ -195,7 +202,8 @@ def manifest_get_embed_info(self, target_desc, ld_args):
- 
- # always monkeypatch it in even though it will only be called in 2.7
- # and 3.2+.
--MSVCCompiler.manifest_get_embed_info = manifest_get_embed_info
-+if not build_mingw32:
-+    MSVCCompiler.manifest_get_embed_info = manifest_get_embed_info
- 
- def monkeypatched_spawn(self, cmd):
-     is_link = cmd[0].endswith("link.exe") or cmd[0].endswith('"link.exe"')
-@@ -239,8 +247,9 @@ def monkeypatched_link(self, target_desc, objects, output_filename, *args, **kw)
-         return self._orig_link(target_desc, objects, output_filename, *args, **kw)
-     finally:
-         delattr(self, '_want_assembly_kept')
--MSVCCompiler.spawn = monkeypatched_spawn
--MSVCCompiler.link = monkeypatched_link
-+if not build_mingw32:
-+    MSVCCompiler.spawn = monkeypatched_spawn
-+    MSVCCompiler.link = monkeypatched_link
- 
- 
- sdk_info = find_platform_sdk_dir()
-@@ -449,6 +458,18 @@ class WinExt (Extension):
-                 # Unicode, Windows executables seem to need this magic:
-                 if "/SUBSYSTEM:WINDOWS" in self.extra_link_args:
-                     self.extra_link_args.append("/ENTRY:wWinMainCRTStartup")
-+        else:
-+            self.extra_compile_args.append("-fpermissive")
-+            unicode_mode = self.unicode_mode
-+            if unicode_mode is None:
-+                unicode_mode = is_py3k
-+            if unicode_mode:
-+                self.extra_compile_args.append("-DUNICODE")
-+                self.extra_compile_args.append("-D_UNICODE")
-+                self.extra_compile_args.append("-DWINNT")
-+                # Unicode, Windows executables seem to need this magic:
-+                #if "/SUBSYSTEM:WINDOWS" in self.extra_link_args:
-+                #    self.extra_link_args.append("/ENTRY:wWinMainCRTStartup")
- 
- class WinExt_pythonwin(WinExt):
-     def __init__ (self, name, **kw):
-@@ -641,7 +662,7 @@ class my_build_ext(build_ext):
-         # The pywintypes library is created in the build_temp
-         # directory, so we need to add this to library_dirs
-         self.library_dirs.append(self.build_temp)
--        self.mingw32 = (self.compiler == "mingw32")
-+        self.mingw32 = build_mingw32
-         if self.mingw32:
-             self.libraries.append("stdc++")
- 
-@@ -698,7 +719,8 @@ class my_build_ext(build_ext):
-             self.compiler.add_include_dir(extra)
-         # and again for lib dirs.
-         for extra in sdk_info["lib"]:
--            extra = os.path.join(extra, 'x64' if is_64bit else 'x86')
-+            if not build_mingw32:
-+                extra = os.path.join(extra, 'x64' if is_64bit else 'x86')
-             assert os.path.isdir(extra), extra
-             assert extra not in self.library_dirs # see above
-             assert os.path.isdir(extra), "%s doesn't exist!" % (extra,)
-@@ -714,7 +736,7 @@ class my_build_ext(build_ext):
-         # includes interfaces for 64-bit builds.
-         if self.plat_name == 'win-amd64' and ext.name == 'exchdapi':
-             return "No 64-bit library for utility functions available."
--        if get_build_version() >=14:
-+        if not build_mingw32 and get_build_version() >=14:
-             if ext.name == 'exchange':
-                 ext.libraries.append('legacy_stdio_definitions')
-             elif ext.name == 'exchdapi':
-@@ -758,7 +780,8 @@ class my_build_ext(build_ext):
- 
-         # We update the .libraries list with the resolved library name.
-         # This is really only so "_d" works.
--        ext.libraries = patched_libs
-+        if not build_mingw32:
-+            ext.libraries = patched_libs
-         return None # no reason - it can be built!
- 
-     def _build_scintilla(self):
-@@ -972,11 +995,16 @@ class my_build_ext(build_ext):
-         if sys.version_info > (2, 7) and sys.version_info < (3, 3):
-             # only stuff built with msvc9 needs this loader.
-             self._build_pycom_loader()
--        self._build_scintilla()
-+        if not build_mingw32:
-+            self._build_scintilla()
-         # Copy cpp lib files needed to create Python COM extensions
--        clib_files = (['win32', 'pywintypes%s.lib'],
--                      ['win32com', 'pythoncom%s.lib'],
--                      ['win32com', 'axscript%s.lib'])
-+        if build_mingw32:
-+            clib_files = (['win32', 'libpywintypes%s.a'],
-+                          ['win32com', 'libpythoncom%s.a'])
-+        else:
-+            clib_files = (['win32', 'pywintypes%s.lib'],
-+                          ['win32com', 'pythoncom%s.lib'],
-+                          ['win32com', 'axscript%s.lib'])
-         for clib_file in clib_files:
-             target_dir = os.path.join(self.build_lib, clib_file[0], "libs")
-             if not os.path.exists(target_dir):
-@@ -988,6 +1016,8 @@ class my_build_ext(build_ext):
-             self.copy_file(os.path.join(self.build_temp, fname),
-                            target_dir
-                            )
-+        if build_mingw32:
-+            return
-         # The MFC DLLs.
-         target_dir = os.path.join(self.build_lib, "pythonwin")
- 
-@@ -1081,9 +1111,13 @@ class my_build_ext(build_ext):
-         # this, distutils gets confused, as they both try and use the same
-         # .obj.
-         output_dir = os.path.join(self.build_temp, ext.name)
-+        if build_mingw32:
-+            include_dirs = [output_dir, os.path.join(output_dir, "win32", "src")] + ext.include_dirs
-+        else:
-+            include_dirs = ext.include_dirs
-         kw = {'output_dir': output_dir,
-               'macros': macros,
--              'include_dirs': ext.include_dirs,
-+              'include_dirs': include_dirs,
-               'debug': self.debug,
-               'extra_postargs': extra_args,
-               'depends': ext.depends,
-@@ -1115,6 +1149,7 @@ class my_build_ext(build_ext):
-                'extra_postargs': extra_args,
-                'debug': self.debug,
-                'build_temp': self.build_temp,
-+               'extra_preargs': []
-         }
- 
-         # Detect target language, if not provided
-@@ -1162,22 +1197,37 @@ class my_build_ext(build_ext):
-         old_build_temp = self.build_temp
-         want_static_crt = sys.version_info > (2,6) and ext.name in static_crt_modules
-         if want_static_crt:
--            self.compiler.compile_options.remove('/MD')
--            self.compiler.compile_options.append('/MT')
--            self.compiler.compile_options_debug.remove('/MDd')
--            self.compiler.compile_options_debug.append('/MTd')
-+            if not build_mingw32:
-+                self.compiler.compile_options.remove('/MD')
-+                self.compiler.compile_options.append('/MT')
-+                self.compiler.compile_options_debug.remove('/MDd')
-+                self.compiler.compile_options_debug.append('/MTd')
- 
-         try:
-+            if build_mingw32:
-+                incs = set()
-+                for source in ext.sources:
-+                    output_dir = os.path.join(self.build_temp, os.path.dirname(source))
-+                    if output_dir not in incs:
-+                        ext.include_dirs.append(output_dir)
-+                        incs.add(output_dir)
-             build_ext.build_extension(self, ext)
-             # XXX This has to be changed for mingw32
-             # Get the .lib files we need.  This is limited to pywintypes,
-             # pythoncom and win32ui - but the first 2 have special names
--            extra = self.debug and "_d.lib" or ".lib"
-+            if build_mingw32:
-+                extra = self.debug and "_d.a" or ".a"
-+            else:
-+                extra = self.debug and "_d.lib" or ".lib"
-             if ext.name in ("pywintypes", "pythoncom"):
-                 # The import libraries are created as PyWinTypes23.lib, but
-                 # are expected to be pywintypes.lib.
--                name1 = "%s%d%d%s" % (ext.name, sys.version_info[0], sys.version_info[1], extra)
--                name2 = "%s%s" % (ext.name, extra)
-+                if build_mingw32:
-+                    name1 = "lib%s%d%d%s" % (ext.name, sys.version_info[0], sys.version_info[1], extra)
-+                    name2 = "lib%s%s" % (ext.name, extra)
-+                else:
-+                    name1 = "%s%d%d%s" % (ext.name, sys.version_info[0], sys.version_info[1], extra)
-+                    name2 = "%s%s" % (ext.name, extra)
-             elif ext.name in ("win32ui",):
-                 name1 = name2 = ext.name + extra
-             else:
-@@ -1199,10 +1249,11 @@ class my_build_ext(build_ext):
-         finally:
-             self.build_temp = old_build_temp
-             if want_static_crt:
--                self.compiler.compile_options.remove('/MT')
--                self.compiler.compile_options.append('/MD')
--                self.compiler.compile_options_debug.remove('/MTd')
--                self.compiler.compile_options_debug.append('/MDd')
-+                if not build_mingw32:
-+                    self.compiler.compile_options.remove('/MT')
-+                    self.compiler.compile_options.append('/MD')
-+                    self.compiler.compile_options_debug.remove('/MTd')
-+                    self.compiler.compile_options_debug.append('/MDd')
- 
-     def get_ext_filename(self, name):
-         # The pywintypes and pythoncom extensions have special names
-@@ -1298,6 +1349,8 @@ class my_build_ext(build_ext):
-         for source in swig_sources:
-             swig_cmd = [swig, "-python", "-c++"]
-             swig_cmd.append("-dnone",) # we never use the .doc files.
-+            if not build_mingw32:
-+                swig_cmd.append("-I" + os.path.abspath("swig/swig_lib/python"))
-             swig_cmd.extend(self.current_extension.extra_swig_commands)
-             if not is_py3k:
-                 swig_cmd.append("-DSWIG_PY2K")
-@@ -1368,7 +1421,10 @@ class my_install(install):
-         if not self.dry_run and not self.root:
-             # We must run the script we just installed into Scripts, as it
-             # may have had 2to3 run over it.
--            filename = os.path.join(self.prefix, "Scripts", "pywin32_postinstall.py")
-+            if build_mingw32:
-+                filename = os.path.join(self.prefix, "bin", "pywin32_postinstall.py")
-+            else:
-+                filename = os.path.join(self.prefix, "Scripts", "pywin32_postinstall.py")
-             if not os.path.isfile(filename):
-                 raise RuntimeError("Can't find '%s'" % (filename,))
-             print("Executing post install script...")
-@@ -1388,18 +1444,25 @@ def my_new_compiler(**kw):
-     return orig_new_compiler(**kw)
- 
- # No way to cleanly wedge our compiler sub-class in.
--from distutils import ccompiler, msvccompiler
-+from distutils import ccompiler
- orig_new_compiler = ccompiler.new_compiler
- ccompiler.new_compiler = my_new_compiler
- 
--base_compiler = msvccompiler.MSVCCompiler
-+if build_mingw32:
-+    from distutils import cygwinccompiler
-+    base_compiler = cygwinccompiler.Mingw32CCompiler
-+else:
-+    from distutils import msvccompiler
-+    base_compiler = msvccompiler.MSVCCompiler
-+
- 
- class my_compiler(base_compiler):
-     # Just one GUIDS.CPP and it gives trouble on mainwin too. Maybe I
-     # should just rename the file, but a case-only rename is likely to be
-     # worse!  This can probably go away once we kill the VS project files
-     # though, as we can just specify the lowercase name in the module def.
--    _cpp_extensions = base_compiler._cpp_extensions + [".CPP"]
-+    if not build_mingw32:
-+        _cpp_extensions = base_compiler._cpp_extensions + [".CPP"]
-     src_extensions = base_compiler.src_extensions + [".CPP"]
- 
-     def link(self,
-@@ -1411,17 +1474,41 @@ class my_compiler(base_compiler):
-               library_dirs=None,
-               runtime_library_dirs=None,
-               export_symbols=None,
--              debug=0, *args, **kw):
--        msvccompiler.MSVCCompiler.link( self,
--                                        target_desc,
--                                        objects,
--                                        output_filename,
--                                        output_dir,
--                                        libraries,
--                                        library_dirs,
--                                        runtime_library_dirs,
--                                        export_symbols,
--                                        debug, *args, **kw)
-+              debug=0, extra_preargs = None, *args, **kw):
-+        if build_mingw32:
-+            temp_dir = os.path.dirname(objects[0])
-+            dll_name = os.path.splitext(os.path.basename(output_filename))[0]
-+            lib_file = os.path.join(temp_dir, 'lib' + dll_name + ".a")
-+            implib_arg="-Wl,--out-implib,%s" % lib_file
-+
-+            if extra_preargs:
-+                extra_preargs.extend(implib_arg)
-+            else:
-+                extra_preargs = [implib_arg]
-+
-+            cygwinccompiler.Mingw32CCompiler.link( self,
-+                                                   target_desc,
-+                                                   objects,
-+                                                   output_filename,
-+                                                   output_dir,
-+                                                   libraries,
-+                                                   library_dirs,
-+                                                   runtime_library_dirs,
-+                                                   export_symbols,
-+                                                   debug, extra_preargs,
-+                                                   *args, **kw)
-+        else:
-+            msvccompiler.MSVCCompiler.link( self,
-+                                            target_desc,
-+                                            objects,
-+                                            output_filename,
-+                                            output_dir,
-+                                            libraries,
-+                                            library_dirs,
-+                                            runtime_library_dirs,
-+                                            export_symbols,
-+                                            debug, *args, **kw)
-+
-         # Here seems a good place to stamp the version of the built
-         # target.  Do this externally to avoid suddenly dragging in the
-         # modules needed by this process, and which we will soon try and
-@@ -1457,6 +1544,45 @@ class my_compiler(base_compiler):
-         if not ok:
-             log.info('Unable to import verstamp, no version info will be added')
- 
-+    if build_mingw32:
-+        def _compile(self, obj, src, ext, cc_args, extra_postargs, pp_opts):
-+            if ext == ".mc":
-+                try:
-+                    basename=os.path.basename(src)[:-3]
-+                    outdir=os.path.dirname(obj)
-+                    self.spawn(["windmc", "-h", outdir, "-r", outdir, src])
-+                    self.spawn(["windres", "-i", 
-+                                os.path.join(outdir, basename + ".rc"),
-+                                "-o", obj])
-+                except DistutilsExecError as msg:
-+                    raise CompileError(msg)
-+            else:
-+                cygwinccompiler.Mingw32CCompiler._compile(self,
-+                                                          obj, src, ext, cc_args,
-+                                                          extra_postargs, pp_opts)
-+
-+        def object_filenames(self, source_filenames, strip_dir=0, output_dir=''):
-+            unproc_src_names = []
-+            obj_names = []
-+            for src_name in source_filenames:
-+                base, ext = os.path.splitext(src_name)
-+                if ext==".mc":
-+                    if unproc_src_names:
-+                        obj_names.extend(cygwinccompiler.Mingw32CCompiler.\
-+                            object_filenames(self, unproc_src_names,
-+                                             strip_dir = strip_dir,
-+                                             output_dir = output_dir))
-+                        unproc_src_names = []
-+                    obj_names.append (os.path.join(output_dir,
-+                                      base + ext + self.obj_extension))
-+                else:
-+                    unproc_src_names.append(src_name)
-+            if unproc_src_names:
-+                obj_names.extend(cygwinccompiler.Mingw32CCompiler.\
-+                    object_filenames(self, unproc_src_names, strip_dir = strip_dir,
-+                                     output_dir = output_dir))
-+            return obj_names
-+
- 
- ################################################################
- 
-@@ -1550,7 +1676,7 @@ for info in (
-             win32/src/win32crypt/PyCRYPTPROV.cpp
-             win32/src/win32crypt/PyCTL_CONTEXT.cpp
-             """),
--        ("win32file", "", None, 0x0500, """
-+        ("win32file", "wsock32 ws2_32" if build_mingw32 else "", None, 0x0500, """
-               win32/src/win32file.i
-               win32/src/win32file_comm.cpp
-               """),
-@@ -1607,7 +1733,7 @@ for info in (
-         sources = info[4].split()
-     extra_compile_args = []
-     ext = WinExt_win32(name,
--                 libraries=lib_names,
-+                 libraries=lib_names + (" pywintypes" if build_mingw32 else ""),
-                  extra_compile_args = extra_compile_args,
-                  windows_h_version = windows_h_ver,
-                  sources = sources,
-@@ -1620,7 +1746,7 @@ win32_extensions += [
-             sources = """
-                 win32\\src\\win32evtlog_messages.mc win32\\src\\win32evtlog.i
-                 """.split(),
--                libraries="advapi32 oleaut32",
-+                libraries="advapi32 oleaut32" + (" pywintypes" if build_mingw32 else ""),
-                 delay_load_libraries="wevtapi",
-                 windows_h_version=0x0600
-         ),
-@@ -1628,7 +1754,7 @@ win32_extensions += [
-            sources = """
-                 win32/src/win32apimodule.cpp win32/src/win32api_display.cpp
-                 """.split(),
--           libraries="user32 advapi32 shell32 version",
-+                 libraries="user32 advapi32 shell32 version" + (" pywintypes" if build_mingw32 else ""),
-            delay_load_libraries="powrprof",
-            windows_h_version=0x0500,
-         ),
-@@ -1638,7 +1764,7 @@ win32_extensions += [
-                 win32/src/win32gui.i
-                """.split(),
-            windows_h_version=0x0500,
--           libraries="gdi32 user32 comdlg32 comctl32 shell32",
-+           libraries="gdi32 user32 comdlg32 comctl32 shell32" + (" pywintypes" if build_mingw32 else ""),
-            define_macros = [("WIN32GUI", None)],
-         ),
-     # winxpgui is built from win32gui.i, but sets up different #defines before
-@@ -1648,7 +1774,7 @@ win32_extensions += [
-                 win32/src/winxpgui.rc win32/src/win32dynamicdialog.cpp
-                 win32/src/win32gui.i
-                """.split(),
--           libraries="gdi32 user32 comdlg32 comctl32 shell32",
-+           libraries="gdi32 user32 comdlg32 comctl32 shell32" + (" pywintypes" if build_mingw32 else ""),
-            windows_h_version=0x0500,
-            define_macros = [("WIN32GUI",None), ("WINXPGUI",None)],
-            extra_swig_commands=["-DWINXPGUI"],
-@@ -1656,7 +1782,7 @@ win32_extensions += [
-     # winxptheme
-     WinExt_win32("_winxptheme",
-            sources = ["win32/src/_winxptheme.i"],
--           libraries="gdi32 user32 comdlg32 comctl32 shell32 Uxtheme",
-+           libraries="gdi32 user32 comdlg32 comctl32 shell32 Uxtheme" + (" pywintypes" if build_mingw32 else ""),
-            windows_h_version=0x0500,
-         ),
- ]
-@@ -1664,7 +1790,7 @@ win32_extensions += [
-     WinExt_win32('servicemanager',
-            sources = ["win32/src/PythonServiceMessages.mc", "win32/src/PythonService.cpp"],
-            extra_compile_args = ['-DPYSERVICE_BUILD_DLL'],
--           libraries = "user32 ole32 advapi32 shell32",
-+           libraries = "user32 ole32 advapi32 shell32" + (" pywintypes" if build_mingw32 else ""),
-            windows_h_version = 0x500,
-            unicode_mode=True,),
- ]
-@@ -1695,7 +1821,8 @@ dirs = {
- 
- # The COM modules.
- pythoncom = WinExt_system32('pythoncom',
--                   sources=("""
-+                   sources=((("%(win32com)s/initguid.cpp"  if build_mingw32 else "") +
-+                        """
-                         %(win32com)s/dllmain.cpp            %(win32com)s/ErrorUtils.cpp
-                         %(win32com)s/MiscTypes.cpp          %(win32com)s/oleargs.cpp
-                         %(win32com)s/PyComHelpers.cpp       %(win32com)s/PyFactory.cpp
-@@ -1737,7 +1864,7 @@ pythoncom = WinExt_system32('pythoncom',
-                         %(win32com)s/extensions/PyICancelMethodCalls.cpp    %(win32com)s/extensions/PyIContext.cpp
-                         %(win32com)s/extensions/PyIEnumContextProps.cpp     %(win32com)s/extensions/PyIClientSecurity.cpp
-                         %(win32com)s/extensions/PyIServerSecurity.cpp
--                        """ % dirs).split(),
-+                        """) % dirs).split(),
-                    depends=("""
-                         %(win32com)s/include\\propbag.h          %(win32com)s/include\\PyComTypeObjects.h
-                         %(win32com)s/include\\PyFactory.h        %(win32com)s/include\\PyGConnectionPoint.h
-@@ -1763,7 +1890,7 @@ pythoncom = WinExt_system32('pythoncom',
-                         %(win32com)s/include\\PyIEnumContextProps.h     %(win32com)s/include\\PyIClientSecurity.h
-                         %(win32com)s/include\\PyIServerSecurity.h
-                         """ % dirs).split(),
--                   libraries = "oleaut32 ole32 user32 urlmon",
-+                   libraries = "oleaut32 ole32 user32 urlmon uuid" + (" pywintypes" if build_mingw32 else ""),
-                    export_symbol_file = 'com/win32com/src/PythonCOM.def',
-                    extra_compile_args = ['-DBUILD_PYTHONCOM'],
-                    pch_header = "stdafx.h",
-@@ -1788,7 +1915,7 @@ com_extensions += [
-                         %(adsi)s/PyIADs.cpp
-                         """ % dirs).split()),
-     WinExt_win32com('axcontrol', pch_header="axcontrol_pch.h",
--                    sources=("""
-+                    sources=(("""
-                         %(axcontrol)s/AXControl.cpp
-                         %(axcontrol)s/PyIOleControl.cpp          %(axcontrol)s/PyIOleControlSite.cpp
-                         %(axcontrol)s/PyIOleInPlaceActiveObject.cpp
-@@ -1799,10 +1926,11 @@ com_extensions += [
-                         %(axcontrol)s/PyIOleClientSite.cpp       %(axcontrol)s/PyIOleInPlaceSite.cpp
-                         %(axcontrol)s/PyIOleObject.cpp           %(axcontrol)s/PyIViewObject2.cpp
-                         %(axcontrol)s/PyIOleCommandTarget.cpp
--                        """ % dirs).split()),
-+                        """ + ("%(axcontrol)s/initguid.cpp" if build_mingw32 else "")) % dirs).split(),
-+                        libraries="pythoncom pywintypes"),
-     WinExt_win32com('axscript',
--                    sources=("""
--                        %(axscript)s/AXScript.cpp
-+                    sources=(("""
-+                        %(axscript)s/AXScript.cpp                %(axscript)s/initguid.cpp
-                         %(axscript)s/GUIDS.CPP                   %(axscript)s/PyGActiveScript.cpp
-                         %(axscript)s/PyGActiveScriptError.cpp    %(axscript)s/PyGActiveScriptParse.cpp
-                         %(axscript)s/PyGActiveScriptSite.cpp     %(axscript)s/PyGObjectSafety.cpp
-@@ -1810,7 +1938,7 @@ com_extensions += [
-                         %(axscript)s/PyIActiveScriptParse.cpp    %(axscript)s/PyIActiveScriptParseProcedure.cpp
-                         %(axscript)s/PyIActiveScriptSite.cpp     %(axscript)s/PyIMultiInfos.cpp
-                         %(axscript)s/PyIObjectSafety.cpp         %(axscript)s/stdafx.cpp
--                        """ % dirs).split(),
-+                        """ + ("%(axscript)s/initguid.cpp" if build_mingw32 else "")) % dirs).split(),
-                     depends=("""
-                              %(axscript)s/AXScript.h
-                              %(axscript)s/guids.h                %(axscript)s/PyGActiveScriptError.h
-@@ -1820,7 +1948,8 @@ com_extensions += [
-                              """ % dirs).split(),
-                     extra_compile_args = ['-DPY_BUILD_AXSCRIPT'],
-                     implib_name="axscript",
--                    pch_header = "stdafx.h"
-+                    pch_header = "stdafx.h",
-+                    libraries="pythoncom pywintypes" if build_mingw32 else ""
-     ),
-     WinExt_win32com('axdebug',
-             libraries="axscript",
-@@ -1870,17 +1999,17 @@ com_extensions += [
-                     %(axdebug)s/PyIRemoteDebugApplicationEvents.cpp
-                     %(axdebug)s/PyIRemoteDebugApplicationThread.cpp
-                     %(axdebug)s/stdafx.cpp
--                     """ % dirs).split(),
--    ),
-+                     """ % dirs).split() ),
-     WinExt_win32com('internet', pch_header="internet_pch.h",
--                    sources=("""
-+                    sources=(("""
-                         %(internet)s/internet.cpp                   %(internet)s/PyIDocHostUIHandler.cpp
-                         %(internet)s/PyIHTMLOMWindowServices.cpp    %(internet)s/PyIInternetBindInfo.cpp
-                         %(internet)s/PyIInternetPriority.cpp        %(internet)s/PyIInternetProtocol.cpp
-                         %(internet)s/PyIInternetProtocolInfo.cpp    %(internet)s/PyIInternetProtocolRoot.cpp
-                         %(internet)s/PyIInternetProtocolSink.cpp    %(internet)s/PyIInternetSecurityManager.cpp
--                    """ % dirs).split(),
--                    depends=["%(internet)s/internet_pch.h" % dirs]),
-+                    """ + ("%(internet)s/initguid.cpp"  if build_mingw32 else "")) % dirs).split(),
-+                    depends=["%(internet)s/internet_pch.h" % dirs],
-+                    libraries="pythoncom pywintypes" if build_mingw32 else ""),
-     WinExt_win32com('mapi', libraries="advapi32", pch_header="PythonCOM.h",
-                     include_dirs=["%(mapi)s/mapi_headers" % dirs],
-                     optional_headers=['edkmdb.h', 'edkguid.h'],
-@@ -1929,9 +2058,10 @@ com_extensions += [
-                                   %(mapi)s/mapi_stub_library/MapiStubLibrary.cpp
-                                   %(mapi)s/mapi_stub_library/StubUtils.cpp
-                                   """ % dirs).split()),
--    WinExt_win32com('shell', libraries='shell32', pch_header="shell_pch.h",
-+
-+    WinExt_win32com('shell', libraries=('pythoncom pywintypes ' if build_mingw32 else '') + 'shell32', pch_header="shell_pch.h",
-                     windows_h_version = 0x600,
--                    sources=("""
-+                    sources=(("""
-                         %(shell)s/PyIActiveDesktop.cpp
-                         %(shell)s/PyIApplicationDestinations.cpp
-                         %(shell)s/PyIApplicationDocumentLists.cpp
-@@ -1956,8 +2086,6 @@ com_extensions += [
-                         %(shell)s/PyIEnumObjects.cpp
-                         %(shell)s/PyIEnumResources.cpp
-                         %(shell)s/PyIEnumShellItems.cpp
--                        %(shell)s/PyIEmptyVolumeCache.cpp
--                        %(shell)s/PyIEmptyVolumeCacheCallBack.cpp
-                         %(shell)s/PyIExplorerBrowser.cpp
-                         %(shell)s/PyIExplorerBrowserEvents.cpp
-                         %(shell)s/PyIExplorerCommand.cpp
-@@ -2002,8 +2130,9 @@ com_extensions += [
-                         %(shell)s/PyITransferSource.cpp
-                         %(shell)s/PyIUniformResourceLocator.cpp
-                         %(shell)s/shell.cpp
--
--                        """ % dirs).split()),
-+                        """ + ("%(shell)s/initguid.cpp" if build_mingw32 else
-+                               "%(shell)s/PyIEmptyVolumeCache.cpp %(shell)s/PyIEmptyVolumeCacheCallBack.cpp"))
-+                             % dirs).split()),
- 
-     WinExt_win32com('propsys', libraries='propsys', delay_load_libraries='shell32',
-                     unicode_mode=True,
-@@ -2031,9 +2160,8 @@ com_extensions += [
-                     implib_name="pypropsys",
-                     ),
- 
--
--    WinExt_win32com('taskscheduler', libraries='mstask',
--                    sources=("""
-+    WinExt_win32com('taskscheduler', libraries='mstask' + (' pythoncom pywintypes'  if build_mingw32 else ''),
-+                    sources=(("""
-                         %(taskscheduler)s/taskscheduler.cpp
-                         %(taskscheduler)s/PyIProvideTaskPage.cpp
-                         %(taskscheduler)s/PyIScheduledWorkItem.cpp
-@@ -2041,7 +2169,7 @@ com_extensions += [
-                         %(taskscheduler)s/PyITaskScheduler.cpp
-                         %(taskscheduler)s/PyITaskTrigger.cpp
- 
--                        """ % dirs).split()),
-+                        """ + ("%(taskscheduler)s/initguid.cpp" if build_mingw32 else ""))% dirs).split()),
-     WinExt_win32com('bits', libraries='Bits', pch_header="bits_pch.h",
-                     sources=("""
-                         %(bits)s/bits.cpp
-@@ -2077,12 +2205,12 @@ com_extensions += [
-                         %(directsound)s/PyIDirectSoundCaptureBuffer.h %(directsound)s/PyIDirectSoundNotify.h
-                         """ % dirs).split(),
-                     optional_headers = ['dsound.h'],
--                    libraries='user32 dsound dxguid'),
--    WinExt_win32com('authorization', libraries='aclui advapi32',
-+                    libraries=('pythoncom pywintypes ' if build_mingw32 else '') + 'user32 dsound dxguid uuid'),
-+    WinExt_win32com('authorization', libraries=('pythoncom pywintypes ' if build_mingw32 else '') + 'aclui advapi32',
-                     sources=("""
-                         %(authorization)s/authorization.cpp
-                         %(authorization)s/PyGSecurityInformation.cpp
--                        """ % dirs).split()),
-+                        """ % dirs).split())
- ]
- 
- pythonwin_extensions = [
-@@ -2253,20 +2381,24 @@ other_extensions.append(
- W32_exe_files = [
-     WinExt_win32("pythonservice",
-          sources=[os.path.join("win32", "src", s) for s in
--                  "PythonService.cpp PythonService.rc".split()],
-+                  (("PythonServiceMessages.mc " if build_mingw32 else "") + "PythonService.cpp PythonService.rc").split()],
-          unicode_mode = True,
--         extra_link_args=["/SUBSYSTEM:CONSOLE"],
--         libraries = "user32 advapi32 ole32 shell32"),
--    WinExt_pythonwin("Pythonwin",
--        sources = [
--            "Pythonwin/pythonwin.cpp",
--            "Pythonwin/pythonwin.rc",
--            "Pythonwin/stdafxpw.cpp",
--            ],
--        extra_link_args=["/SUBSYSTEM:WINDOWS"],
--        optional_headers=['afxres.h']),
-+         extra_link_args=[] if build_mingw32 else ["/SUBSYSTEM:CONSOLE"],
-+         libraries = ("pywintypes " if build_mingw32 else "") + "user32 advapi32 ole32 shell32")
- ]
- 
-+if not build_mingw32:
-+    W32_exe_files.append(
-+        WinExt_pythonwin("Pythonwin",
-+            sources = [
-+                "Pythonwin/pythonwin.cpp",
-+                "Pythonwin/pythonwin.rc",
-+                "Pythonwin/stdafxpw.cpp",
-+            ],
-+            extra_link_args=["/SUBSYSTEM:WINDOWS"],
-+            optional_headers=['afxres.h'])
-+        )
-+
- # Special definitions for SWIG.
- swig_interface_parents = {
-     # source file base,     "base class" for generated COM support
-@@ -2415,7 +2547,10 @@ packages=['win32com',
-           ]
- 
- py_modules = expand_modules("win32\\lib")
--ext_modules = win32_extensions + com_extensions + pythonwin_extensions + \
-+if build_mingw32:
-+    ext_modules = win32_extensions + com_extensions + other_extensions
-+else:
-+    ext_modules = win32_extensions + com_extensions + pythonwin_extensions + \
-                     other_extensions
- 
- # Build a map of DLL base addresses.  According to Python's PC\dllbase_nt.txt,
-diff --git a/win32/src/PerfMon/perfmondata.cpp b/win32/src/PerfMon/perfmondata.cpp
-index 23e7557..c456d89 100644
---- a/win32/src/PerfMon/perfmondata.cpp
-+++ b/win32/src/PerfMon/perfmondata.cpp
-@@ -89,10 +89,19 @@ PPERF_COUNTER_BLOCK pCounterBlock;
- //      these are used to insure that the data collection functions
- //      accessed by Perflib will have the correct calling format.
- //
-+
-+#if defined(__MINGW32__)
-+extern "C" {
-+#endif
-+
- PM_OPEN_PROC   OpenPerformanceData;
- PM_COLLECT_PROC    CollectPerformanceData;
- PM_CLOSE_PROC  ClosePerformanceData;
- 
-+#if defined(__MINGW32__)
-+}
-+#endif
-+
- TCHAR szFullModulePath[MAX_PATH];
- TCHAR szModuleName[MAX_PATH]; // will point into the buffer above.
- 
-@@ -130,6 +139,9 @@ BOOL WINAPI DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID lpReserved)
- 
- 
- 
-+#if defined(__MINGW32__)
-+extern "C"
-+#endif
- DWORD APIENTRY OpenPerformanceData( LPWSTR lpDeviceNames )
- /*++
-     Routine Description:
-@@ -278,6 +290,9 @@ OpenExitPoint:
- 	return status;
- }
- 
-+#if defined(__MINGW32__)
-+extern "C"
-+#endif
- DWORD APIENTRY CollectPerformanceData(
-     IN      LPWSTR  lpValueName,
- 	IN OUT  LPVOID  *lppData,
-@@ -379,6 +394,9 @@ Arguments:   IN       LPWSTR   lpValueName
-     return ERROR_SUCCESS;
- }
- 
-+#if defined(__MINGW32__)
-+extern "C"
-+#endif
- DWORD APIENTRY ClosePerformanceData()
- /*++
- Routine Description:
-@@ -445,7 +463,11 @@ HANDLE MonOpenEventLog (const TCHAR *szSourceName)
- --*/
- {
-     HKEY hAppKey;
-+#if defined(__MINGW32__)
-+    TCHAR LogLevelKeyName[] = _T("SOFTWARE\\Microsoft\\Windows_NT\\CurrentVersion\\Perflib");
-+#else
-     TCHAR LogLevelKeyName[] = _T("SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Perflib");
-+#endif
- 
-     TCHAR LogLevelValueName[] = _T("EventLogLevel");
- 	LONG lStatus;
-diff --git a/win32/src/PySECURITY_DESCRIPTOR.cpp b/win32/src/PySECURITY_DESCRIPTOR.cpp
-index 218daf9..2873603 100644
---- a/win32/src/PySECURITY_DESCRIPTOR.cpp
-+++ b/win32/src/PySECURITY_DESCRIPTOR.cpp
-@@ -6,6 +6,10 @@
- #include "PySecurityObjects.h"
- #include "structmember.h"
- 
-+#if defined(__MINGW32__)
-+#include <algorithm>
-+#endif
-+
- #ifndef NO_PYWINTYPES_SECURITY
- BOOL (WINAPI *setsecuritydescriptorcontrol)(PSECURITY_DESCRIPTOR, SECURITY_DESCRIPTOR_CONTROL, SECURITY_DESCRIPTOR_CONTROL)=NULL;
- 
-@@ -786,7 +790,11 @@ PySECURITY_DESCRIPTOR::PySECURITY_DESCRIPTOR(Py_ssize_t cb /*= 0*/)
- {
- 	ob_type = &PySECURITY_DESCRIPTORType;
- 	_Py_NewReference(this);
-+#if defined(__MINGW32__)
-+	cb = std::max(cb, static_cast<Py_ssize_t>(SECURITY_DESCRIPTOR_MIN_LENGTH));
-+#else
- 	cb = max(cb, SECURITY_DESCRIPTOR_MIN_LENGTH);
-+#endif
- 	PSECURITY_DESCRIPTOR psd = malloc(cb);
- 	this->m_psd=NULL;
- 	if (::InitializeSecurityDescriptor(psd, SECURITY_DESCRIPTOR_REVISION))
-diff --git a/win32/src/PyWinTypes.h b/win32/src/PyWinTypes.h
-index 00ac8a1..a5fc23e 100644
---- a/win32/src/PyWinTypes.h
-+++ b/win32/src/PyWinTypes.h
-@@ -393,8 +393,13 @@ PYWINTYPES_EXPORT PyObject *PyWinObject_FromULARGE_INTEGER(ULARGE_INTEGER &val);
- // We also happen to know a LARGE_INTEGER is an __int64, so do it the easy way
- #define PyWinObject_AsPY_LONG_LONG(ob, pResult) PyWinObject_AsLARGE_INTEGER((ob), (LARGE_INTEGER *)(pResult))
- #define PyWinObject_AsUPY_LONG_LONG(ob, pResult) PyWinObject_AsULARGE_INTEGER((ob), (ULARGE_INTEGER *)(pResult))
-+#if defined(__MINGW32__)
-+#define PyWinObject_FromPY_LONG_LONG(val) PyWinObject_FromLARGE_INTEGER(val)
-+#define PyWinObject_FromUPY_LONG_LONG(val) PyWinObject_FromULARGE_INTEGER(val)
-+#else
- #define PyWinObject_FromPY_LONG_LONG(val) PyWinObject_FromLARGE_INTEGER((LARGE_INTEGER)val)
- #define PyWinObject_FromUPY_LONG_LONG(val) PyWinObject_FromULARGE_INTEGER((ULARGE_INTEGER)val)
-+#endif
- 
- // A DWORD_PTR and ULONG_PTR appear to mean "integer long enough to hold a pointer"
- // It is *not* actually a pointer (but is the same size as a pointer)
-@@ -797,7 +802,7 @@ private:
- 
- // A helper for simple exception handling.
- // try/__try
--#ifdef MAINWIN
-+#if defined(__MINGW32__) || defined(MAINWIN)
- #define PYWINTYPES_TRY try
- #else
- #define PYWINTYPES_TRY __try
-diff --git a/win32/src/PyWinTypesmodule.cpp b/win32/src/PyWinTypesmodule.cpp
-index e136fff..77e10a4 100644
---- a/win32/src/PyWinTypesmodule.cpp
-+++ b/win32/src/PyWinTypesmodule.cpp
-@@ -1140,7 +1140,11 @@ BOOL WINAPI DllMain(HANDLE hInstance, DWORD dwReason, LPVOID lpReserved)
- }
- 
- // Function to format a python traceback into a character string.
-+#if defined(__MINGW32__)
-+#define GPEM_ERROR(what) {errorMsg = "<Error getting traceback - " what ">";goto done;}
-+#else
- #define GPEM_ERROR(what) {errorMsg = "<Error getting traceback - " ## what ## ">";goto done;}
-+#endif
- char *GetPythonTraceback(PyObject *exc_type, PyObject *exc_value, PyObject *exc_tb)
- {
- 	// Sleep (30000); // Time enough to attach the debugger (barely)
-diff --git a/win32/src/PythonService.cpp b/win32/src/PythonService.cpp
-index c7b7531..8a9121d 100644
---- a/win32/src/PythonService.cpp
-+++ b/win32/src/PythonService.cpp
-@@ -302,7 +302,11 @@ static PyObject *PySetEventSourceName(PyObject *self, PyObject *args)
- 	if (!PyWinObject_AsTCHAR(obName, &msg))
- 		return NULL;
- 	_tcsncpy(g_szEventSourceName, msg,
-+#if defined(__MINGW32__)
-+			 sizeof(g_szEventSourceName)/sizeof(TCHAR));
-+#else
- 			 sizeof g_szEventSourceName/sizeof TCHAR);
-+#endif
- 	PyWinObject_FreeTCHAR(msg);
- 	g_bRegisteredEventSource = FALSE; // so this name re-registered.
- 	if (registerNow)
-@@ -680,10 +684,18 @@ BOOL PythonService_Initialize( const TCHAR *evtsrc_name, const TCHAR *evtsrc_fil
- {
- 	if (evtsrc_name && *evtsrc_name)
- 		_tcsncpy(g_szEventSourceName, evtsrc_name,
-+#if defined(__MINGW32__)
-+				 sizeof(g_szEventSourceName)/sizeof(TCHAR));
-+#else
- 				 sizeof g_szEventSourceName/sizeof TCHAR);
-+#endif
- 	if (evtsrc_file && *evtsrc_file)
- 		_tcsncpy(g_szEventSourceFileName, evtsrc_file,
-+#if defined(__MINGW32__)
-+				 sizeof(g_szEventSourceFileName)/sizeof(TCHAR));
-+#else
- 				 sizeof g_szEventSourceFileName/sizeof TCHAR);
-+#endif
- 	return TRUE;
- }
- 
-@@ -1443,7 +1455,11 @@ static void CheckRegisterEventSourceFile()
- 
- 	if (!g_szEventSourceFileName[0])
- 		GetModuleFileName(g_hdll, g_szEventSourceFileName,
-+#if defined(__MINGW32__)
-+		                  sizeof(g_szEventSourceFileName)/sizeof(TCHAR));
-+#else
- 		                  sizeof g_szEventSourceFileName/sizeof TCHAR);
-+#endif
- 
- 	HKEY hkey;
- 	TCHAR keyName[MAX_PATH];
-@@ -1549,7 +1565,11 @@ BOOL WINAPI DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID lpReserved)
- #else // PYSERVICE_BUILD_DLL
- // Our EXE entry point.
- 
-+#if defined(__MINGW32__)
-+extern "C" int main(int argc, TCHAR **argv)
-+#else
- int _tmain(int argc, TCHAR **argv)
-+#endif
- {
- 	PyObject *module, *f;
- 	PyThreadState *threadState;
-diff --git a/win32/src/PythonServiceMessages.mc b/win32/src/PythonServiceMessages.mc
-index ef26675..c8787a4 100644
---- a/win32/src/PythonServiceMessages.mc
-+++ b/win32/src/PythonServiceMessages.mc
-@@ -134,6 +134,7 @@ MessageId=0x7
- Severity=Error
- SymbolicName=E_UNUSED2
- Language=English
-+%1
- .
- 
- MessageId=0x8
-diff --git a/win32/src/odbc.cpp b/win32/src/odbc.cpp
-index c58aef5..9d3dc35 100644
---- a/win32/src/odbc.cpp
-+++ b/win32/src/odbc.cpp
-@@ -18,6 +18,10 @@
- #include "PyWinObjects.h"
- #include "structmember.h"
- 
-+#if defined(__MINGW32__)
-+#include <algorithm>
-+#endif
-+
- #include <sql.h>
- #include <sqlext.h>
- 
-@@ -105,96 +109,10 @@ static cursorObject *cursor(PyObject *o)
- }
- 
- static void cursorDealloc(PyObject *self);
--PyMethodDef cursorMethods[];
--PyMemberDef cursorMembers[];
- 
--static PyTypeObject Cursor_Type =
--{
--	PYWIN_OBJECT_HEAD
--	"odbccur",				/*tp_name */
--	sizeof(cursorObject),	/*tp_basicsize */
--	0,						/*tp_itemsize */
--	cursorDealloc,			/*tp_dealloc */
--	0,						/*tp_print */
--	0,						/*tp_getattr */
--	0,						/*tp_setattr */
--	0,						/*tp_compare */
--	0,						/*tp_repr */
--	0,						/*tp_as_number */
--	0,						/* tp_as_sequence */
--	0,						/* tp_as_mapping */
--	0,						/* tp_hash */
--	0,						/* tp_call */
--	0,						/*tp_str */
--	PyObject_GenericGetAttr,	/* tp_getattro dbiGetAttr */
--	PyObject_GenericSetAttr,	/* tp_setattro */
--	0,						/*tp_as_buffer*/
--	Py_TPFLAGS_DEFAULT,		/* tp_flags */
--	0,						/* tp_doc */
--	0,						/* tp_traverse */
--	0,						/* tp_clear */
--	0,						/* tp_richcompare */
--	0,						/* tp_weaklistoffset */
--	0,						/* tp_iter */
--	0,						/* tp_iternext */
--	cursorMethods,			/* tp_methods */
--	cursorMembers,			/* tp_members */
--	0,						/* tp_getset */
--	0,						/* tp_base */
--	0,						/* tp_dict */
--	0,						/* tp_descr_get */
--	0,						/* tp_descr_set */
--	0,						/* tp_dictoffset */
--	0,						/* tp_init */
--	0,						/* tp_alloc */
--	0,						/* tp_new */
--};
- 
- 
- static void connectionDealloc(PyObject *self);
--PyMethodDef connectionMethods[];
--PyMemberDef connectionMembers[];
--static PyTypeObject Connection_Type =
--{
--	PYWIN_OBJECT_HEAD
--	"odbcconn",				/*tp_name */
--	sizeof (connectionObject),	/*tp_basicsize */
--	0,						/*tp_itemsize */
--	connectionDealloc,		/*tp_dealloc */
--	0,						/*tp_print */
--	0,						/*tp_getattr */
--	0,						/*tp_setattr */
--	0,						/*tp_compare */
--	0,						/*tp_repr */
--	0,						/*tp_as_number */
--	0,						/* tp_as_sequence */
--	0,						/* tp_as_mapping */
--	0,						/* tp_hash */
--	0,						/* tp_call */
--	0,						/*tp_str */
--	PyObject_GenericGetAttr,	/* tp_getattro dbiGetAttr */
--	PyObject_GenericSetAttr,	/* tp_setattro */
--	0,						/*tp_as_buffer*/
--	Py_TPFLAGS_DEFAULT,		/* tp_flags */
--	0,						/* tp_doc */
--	0,						/* tp_traverse */
--	0,						/* tp_clear */
--	0,						/* tp_richcompare */
--	0,						/* tp_weaklistoffset */
--	0,						/* tp_iter */
--	0,						/* tp_iternext */
--	connectionMethods,		/* tp_methods */
--	connectionMembers,		/* tp_members */
--	0,						/* tp_getset */
--	0,						/* tp_base */
--	0,						/* tp_dict */
--	0,						/* tp_descr_get */
--	0,						/* tp_descr_set */
--	0,						/* tp_dictoffset */
--	0,						/* tp_init */
--	0,						/* tp_alloc */
--	0,						/* tp_new */
--};
- 
- static int unsuccessful(RETCODE rc)
- {
-@@ -334,144 +252,6 @@ static int attemptReconnect(cursorObject *cur)
- }
- 
- 
--/* @pymethod |connection|setautocommit|Sets the autocommit mode. */
--static PyObject *odbcSetAutoCommit(PyObject *self, PyObject *args)
--{
--	int c;
--	connectionObject *conn;
--	/* @pyparm int|c||The boolean autocommit mode. */
--	if (!PyArg_ParseTuple(args, "i",&c))
--		return NULL;
--	conn=connection(self);
--	if (c==0)
--	{
--		if (unsuccessful(SQLSetConnectOption(
--			conn->hdbc,
--			SQL_AUTOCOMMIT,
--			SQL_AUTOCOMMIT_OFF)))
--		{
--			connectionError(conn, _T("SETAUTOCOMMIT"));
--			return NULL;
--		}
--	}
--	else
--	{
--		if (unsuccessful(SQLSetConnectOption(
--			conn->hdbc,
--			SQL_AUTOCOMMIT,
--			SQL_AUTOCOMMIT_ON)))
--		{
--			connectionError(conn, _T("SETAUTOCOMMIT"));
--			return NULL;
--		};
--	}
--
--	Py_INCREF(Py_None);
--	return Py_None;
--}
--
--
--/* @pymethod |connection|commit|Commits a transaction. */
--static PyObject *odbcCommit(PyObject *self, PyObject *args)
--{
--	RETCODE rc;
--	Py_BEGIN_ALLOW_THREADS
--	rc = SQLTransact(
--		Env,
--		connection(self)->hdbc,
--		SQL_COMMIT);
--	Py_END_ALLOW_THREADS
--	if (unsuccessful(rc))
--	{
--		connectionError(connection(self), _T("COMMIT"));
--		return 0;
--	}
--	else
--	{
--		Py_INCREF(Py_None);
--		return Py_None;
--	}
--}
--
--/* @pymethod |connection|rollback|Rollsback a transaction. */
--static PyObject *odbcRollback(PyObject *self, PyObject *args)
--{
--	RETCODE rc;
--	Py_BEGIN_ALLOW_THREADS
--	rc = SQLTransact(
--		Env,
--		connection(self)->hdbc,
--		SQL_ROLLBACK);
--	Py_END_ALLOW_THREADS
--	if (unsuccessful(rc))
--	{
--		connectionError(connection(self), _T("ROLLBACK"));
--		return 0;
--	}
--	else {
--		Py_INCREF(Py_None);
--		return Py_None;
--	}
--}
--
--/* @pymethod |connection|cursor|Creates a <o cursor> object */
--static PyObject *odbcCursor(PyObject *self, PyObject *args)
--{
--	connectionObject *conn = connection(self);
--	if (conn->connected == 0)
--	{
--		if (doConnect(conn))
--		{
--			return 0;
--		}
--	}
--
--	cursorObject *cur = PyObject_New(cursorObject, &Cursor_Type);
--	if (cur == NULL)
--		return NULL;
--
--	cur->outputVars = 0;
--	cur->inputVars = 0;
--	cur->description = 0;
--	cur->max_width = 65536L;
--	cur->my_conx = 0;
--	cur->hstmt=NULL;
--	cur->cursorError=odbcError;
--	Py_INCREF(odbcError);
--	if (unsuccessful(SQLAllocStmt(conn->hdbc, &cur->hstmt)))
--	{
--		connectionError(cur->my_conx, _T("OPEN"));
--		Py_DECREF(cur);
--		return NULL;
--	}
--	cur->my_conx = conn;
--	cur->connect_id = cur->my_conx->connect_id;
--	Py_INCREF(self); /* the cursors owns a reference to the connection */
--	return (PyObject*) cur;
--}
--
--/* @pymethod |connection|close|Closes the connection. */
--static PyObject *odbcClose(PyObject *self, PyObject *args)
--{
--  Py_INCREF(Py_None);
--  return Py_None;
--}
--
--/* @object connection|An object representing an ODBC connection */
--static struct PyMethodDef connectionMethods[] = {
--	{ "setautocommit", odbcSetAutoCommit, 1 }, /* @pymeth setautocommit|Sets the autocommit mode. */
--	{ "commit", odbcCommit, 1 } , /* @pymeth commit|Commits a transaction. */
--	{ "rollback", odbcRollback, 1 } , /* @pymeth rollback|Rollsback a transaction. */
--	{ "cursor", odbcCursor, 1 } , /* @pymeth cursor|Creates a <o cursor> object */
--	{ "close", odbcClose, 1 } , /* @pymeth close|Closes the connection. */
--	{0,     0}
--};
--
--static PyMemberDef connectionMembers[] = {
--	{"error", T_OBJECT, offsetof(connectionObject, connectionError), READONLY},
--	{NULL}
--};
--
- static void connectionDealloc(PyObject *self)
- {
- 	Py_XDECREF(connection(self)->connectionError);
-@@ -1192,21 +972,41 @@ static int display_size(short coltype, int collen, const TCHAR *colname)
-     case SQL_DATE:
-     case SQL_TIMESTAMP:
-     case SQL_BIT:
-+#if defined(__MINGW32__)
-+      return(std::max(collen, (int)_tcslen(colname)));
-+#else
-       return(max(collen, (int)_tcslen(colname)));
-+#endif
-     case SQL_SMALLINT:
-     case SQL_INTEGER:
-     case SQL_TINYINT:
-+#if defined(__MINGW32__)
-+      return(std::max(collen+1, (int)_tcslen(colname)));
-+#else
-       return(max(collen+1, (int)_tcslen(colname)));
-+#endif
-     case SQL_DECIMAL:
-     case SQL_NUMERIC:
-+#if defined(__MINGW32__)
-+      return(std::max(collen+2, (int)_tcslen(colname)));
-+#else
-       return(max(collen+2, (int)_tcslen(colname)));
-+#endif
-     case SQL_REAL:
-     case SQL_FLOAT:
-     case SQL_DOUBLE:
-+#if defined(__MINGW32__)
-+      return(std::max(20, (int)_tcslen(colname)));
-+#else
-       return(max(20, (int)_tcslen(colname)));
-+#endif
-     case SQL_BINARY:
-     case SQL_VARBINARY:
-+#if defined(__MINGW32__)
-+      return(std::max(2*collen, (int)_tcslen(colname)));
-+#else
-       return(max(2*collen, (int)_tcslen(colname)));
-+#endif
-     case SQL_LONGVARBINARY:
-     case SQL_LONGVARCHAR:
-     default:
-@@ -1814,6 +1614,226 @@ static PyMemberDef cursorMembers[] = {
- 	{NULL}
- };
- 
-+static PyTypeObject Cursor_Type =
-+{
-+	PYWIN_OBJECT_HEAD
-+	"odbccur",				/*tp_name */
-+	sizeof(cursorObject),	/*tp_basicsize */
-+	0,						/*tp_itemsize */
-+	cursorDealloc,			/*tp_dealloc */
-+	0,						/*tp_print */
-+	0,						/*tp_getattr */
-+	0,						/*tp_setattr */
-+	0,						/*tp_compare */
-+	0,						/*tp_repr */
-+	0,						/*tp_as_number */
-+	0,						/* tp_as_sequence */
-+	0,						/* tp_as_mapping */
-+	0,						/* tp_hash */
-+	0,						/* tp_call */
-+	0,						/*tp_str */
-+	PyObject_GenericGetAttr,	/* tp_getattro dbiGetAttr */
-+	PyObject_GenericSetAttr,	/* tp_setattro */
-+	0,						/*tp_as_buffer*/
-+	Py_TPFLAGS_DEFAULT,		/* tp_flags */
-+	0,						/* tp_doc */
-+	0,						/* tp_traverse */
-+	0,						/* tp_clear */
-+	0,						/* tp_richcompare */
-+	0,						/* tp_weaklistoffset */
-+	0,						/* tp_iter */
-+	0,						/* tp_iternext */
-+	cursorMethods,			/* tp_methods */
-+	cursorMembers,			/* tp_members */
-+	0,						/* tp_getset */
-+	0,						/* tp_base */
-+	0,						/* tp_dict */
-+	0,						/* tp_descr_get */
-+	0,						/* tp_descr_set */
-+	0,						/* tp_dictoffset */
-+	0,						/* tp_init */
-+	0,						/* tp_alloc */
-+	0,						/* tp_new */
-+};
-+/* @pymethod |connection|setautocommit|Sets the autocommit mode. */
-+static PyObject *odbcSetAutoCommit(PyObject *self, PyObject *args)
-+{
-+	int c;
-+	connectionObject *conn;
-+	/* @pyparm int|c||The boolean autocommit mode. */
-+	if (!PyArg_ParseTuple(args, "i",&c))
-+		return NULL;
-+	conn=connection(self);
-+	if (c==0)
-+	{
-+		if (unsuccessful(SQLSetConnectOption(
-+			conn->hdbc,
-+			SQL_AUTOCOMMIT,
-+			SQL_AUTOCOMMIT_OFF)))
-+		{
-+			connectionError(conn, _T("SETAUTOCOMMIT"));
-+			return NULL;
-+		}
-+	}
-+	else
-+	{
-+		if (unsuccessful(SQLSetConnectOption(
-+			conn->hdbc,
-+			SQL_AUTOCOMMIT,
-+			SQL_AUTOCOMMIT_ON)))
-+		{
-+			connectionError(conn, _T("SETAUTOCOMMIT"));
-+			return NULL;
-+		};
-+	}
-+
-+	Py_INCREF(Py_None);
-+	return Py_None;
-+}
-+
-+
-+/* @pymethod |connection|commit|Commits a transaction. */
-+static PyObject *odbcCommit(PyObject *self, PyObject *args)
-+{
-+	RETCODE rc;
-+	Py_BEGIN_ALLOW_THREADS
-+	rc = SQLTransact(
-+		Env,
-+		connection(self)->hdbc,
-+		SQL_COMMIT);
-+	Py_END_ALLOW_THREADS
-+	if (unsuccessful(rc))
-+	{
-+		connectionError(connection(self), _T("COMMIT"));
-+		return 0;
-+	}
-+	else
-+	{
-+		Py_INCREF(Py_None);
-+		return Py_None;
-+	}
-+}
-+
-+/* @pymethod |connection|rollback|Rollsback a transaction. */
-+static PyObject *odbcRollback(PyObject *self, PyObject *args)
-+{
-+	RETCODE rc;
-+	Py_BEGIN_ALLOW_THREADS
-+	rc = SQLTransact(
-+		Env,
-+		connection(self)->hdbc,
-+		SQL_ROLLBACK);
-+	Py_END_ALLOW_THREADS
-+	if (unsuccessful(rc))
-+	{
-+		connectionError(connection(self), _T("ROLLBACK"));
-+		return 0;
-+	}
-+	else {
-+		Py_INCREF(Py_None);
-+		return Py_None;
-+	}
-+}
-+
-+/* @pymethod |connection|cursor|Creates a <o cursor> object */
-+static PyObject *odbcCursor(PyObject *self, PyObject *args)
-+{
-+	connectionObject *conn = connection(self);
-+	if (conn->connected == 0)
-+	{
-+		if (doConnect(conn))
-+		{
-+			return 0;
-+		}
-+	}
-+
-+	cursorObject *cur = PyObject_New(cursorObject, &Cursor_Type);
-+	if (cur == NULL)
-+		return NULL;
-+
-+	cur->outputVars = 0;
-+	cur->inputVars = 0;
-+	cur->description = 0;
-+	cur->max_width = 65536L;
-+	cur->my_conx = 0;
-+	cur->hstmt=NULL;
-+	cur->cursorError=odbcError;
-+	Py_INCREF(odbcError);
-+	if (unsuccessful(SQLAllocStmt(conn->hdbc, &cur->hstmt)))
-+	{
-+		connectionError(cur->my_conx, _T("OPEN"));
-+		Py_DECREF(cur);
-+		return NULL;
-+	}
-+	cur->my_conx = conn;
-+	cur->connect_id = cur->my_conx->connect_id;
-+	Py_INCREF(self); /* the cursors owns a reference to the connection */
-+	return (PyObject*) cur;
-+}
-+
-+/* @pymethod |connection|close|Closes the connection. */
-+static PyObject *odbcClose(PyObject *self, PyObject *args)
-+{
-+  Py_INCREF(Py_None);
-+  return Py_None;
-+}
-+
-+/* @object connection|An object representing an ODBC connection */
-+static struct PyMethodDef connectionMethods[6] = {
-+	{ "setautocommit", odbcSetAutoCommit, 1 }, /* @pymeth setautocommit|Sets the autocommit mode. */
-+	{ "commit", odbcCommit, 1 } , /* @pymeth commit|Commits a transaction. */
-+	{ "rollback", odbcRollback, 1 } , /* @pymeth rollback|Rollsback a transaction. */
-+	{ "cursor", odbcCursor, 1 } , /* @pymeth cursor|Creates a <o cursor> object */
-+	{ "close", odbcClose, 1 } , /* @pymeth close|Closes the connection. */
-+	{0,     0}
-+};
-+
-+static PyMemberDef connectionMembers[2] = {
-+	{"error", T_OBJECT, offsetof(connectionObject, connectionError), READONLY},
-+	{NULL}
-+};
-+
-+static PyTypeObject Connection_Type =
-+{
-+	PYWIN_OBJECT_HEAD
-+	"odbcconn",				/*tp_name */
-+	sizeof (connectionObject),	/*tp_basicsize */
-+	0,						/*tp_itemsize */
-+	connectionDealloc,		/*tp_dealloc */
-+	0,						/*tp_print */
-+	0,						/*tp_getattr */
-+	0,						/*tp_setattr */
-+	0,						/*tp_compare */
-+	0,						/*tp_repr */
-+	0,						/*tp_as_number */
-+	0,						/* tp_as_sequence */
-+	0,						/* tp_as_mapping */
-+	0,						/* tp_hash */
-+	0,						/* tp_call */
-+	0,						/*tp_str */
-+	PyObject_GenericGetAttr,	/* tp_getattro dbiGetAttr */
-+	PyObject_GenericSetAttr,	/* tp_setattro */
-+	0,						/*tp_as_buffer*/
-+	Py_TPFLAGS_DEFAULT,		/* tp_flags */
-+	0,						/* tp_doc */
-+	0,						/* tp_traverse */
-+	0,						/* tp_clear */
-+	0,						/* tp_richcompare */
-+	0,						/* tp_weaklistoffset */
-+	0,						/* tp_iter */
-+	0,						/* tp_iternext */
-+	connectionMethods,		/* tp_methods */
-+	connectionMembers,		/* tp_members */
-+	0,						/* tp_getset */
-+	0,						/* tp_base */
-+	0,						/* tp_dict */
-+	0,						/* tp_descr_get */
-+	0,						/* tp_descr_set */
-+	0,						/* tp_dictoffset */
-+	0,						/* tp_init */
-+	0,						/* tp_alloc */
-+	0,						/* tp_new */
-+};
- static void parseInfo(connectionObject *conn, const TCHAR *c)
- {
- 	TCHAR *p;
-diff --git a/win32/src/win32apimodule.cpp b/win32/src/win32apimodule.cpp
-index f7e36b1..dd5223f 100644
---- a/win32/src/win32apimodule.cpp
-+++ b/win32/src/win32apimodule.cpp
-@@ -817,12 +817,16 @@ PyFormatMessageA(PyObject *self, PyObject *args)
- 	
- 	{
- 	PyW32_BEGIN_ALLOW_THREADS
-+#if !defined(__MINGW32__)
- 	__try{
-+#endif
- 		lrc = ::FormatMessageA(flags, pSource, msgId, langId, (LPSTR)&resultBuf, 0, (va_list *)pInserts );
-+#if !defined(__MINGW32__)
- 		}
- 	__except (GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH){
- 		baccessviolation=TRUE;
- 		}
-+#endif
- 	PyW32_END_ALLOW_THREADS
- 	}
- 
-@@ -927,12 +931,16 @@ PyFormatMessageW(PyObject *self, PyObject *args)
- 
- 	{
- 	PyW32_BEGIN_ALLOW_THREADS
-+#if !defined(__MINGW32__)
- 	__try{
-+#endif
- 		lrc = ::FormatMessageW(flags, pSource, msgId, langId, (LPWSTR)&resultBuf, 0, (va_list *)pInserts );
-+#if !defined(__MINGW32__)
- 		}
- 	__except (GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH){
- 		baccessviolation=TRUE;
- 		}
-+#endif 
- 	PyW32_END_ALLOW_THREADS
- 	}
- 
-@@ -5774,8 +5782,11 @@ static PyObject *PyApply(PyObject *self, PyObject *args)
- 	}
- 	PyThreadState *stateSave = PyThreadState_Swap(NULL);
- 	PyThreadState_Swap(stateSave);
-+#if !defined(__MINGW32__)
- 	_try {
-+#endif
- 		ret = PyObject_CallObject(obFunc, obArgs);
-+#if !defined(__MINGW32__)
- 	}
- 	_except( PyApplyExceptionFilter( GetExceptionCode(),
- 	                                 GetExceptionInformation(),
-@@ -5804,6 +5815,7 @@ static PyObject *PyApply(PyObject *self, PyObject *args)
- 		Py_XDECREF(exc_value);
- 		ret = NULL;
- 	}
-+#endif
- 	return ret;
- // @comm Calls the specified function in a manner similar to 
- // the built-in function apply(), but allows Win32 exceptions
-diff --git a/win32/src/win32crypt/PyCRYPTPROV.cpp b/win32/src/win32crypt/PyCRYPTPROV.cpp
-index 140ddd3..3de895c 100644
---- a/win32/src/win32crypt/PyCRYPTPROV.cpp
-+++ b/win32/src/win32crypt/PyCRYPTPROV.cpp
-@@ -1,6 +1,10 @@
- // @doc
- #include "win32crypt.h"
- 
-+#if defined(__MINGW32__)
-+#include <algorithm>
-+#endif
-+
- // @object PyCRYPTPROV|Handle to a cryptographic provider, created using <om cryptoapi.CryptAcquireContext>
- struct PyMethodDef PyCRYPTPROV::methods[] = {
- 	// @pymeth CryptReleaseContext|Releases the CSP handle
-@@ -351,7 +355,11 @@ PyObject *PyCRYPTPROV::PyCryptGenRandom(PyObject *self, PyObject *args, PyObject
- 	//initialize buffer with char string if passed if
- 	ZeroMemory(pbBuffer, dwLen+1);
- 	if (seeddata != NULL)
-+#if defined(__MINGW32__)
-+		memcpy(pbBuffer, seeddata, std::min(dwLen,seedlen));
-+#else
- 		memcpy(pbBuffer, seeddata, min(dwLen,seedlen));
-+#endif
- 	if (CryptGenRandom(hcryptprov, dwLen, pbBuffer))
- 		ret=PyString_FromStringAndSize((char *)pbBuffer, dwLen);
- 	else
-diff --git a/win32/src/win32crypt/win32cryptmodule.cpp b/win32/src/win32crypt/win32cryptmodule.cpp
-index 29b2c80..5875294 100644
---- a/win32/src/win32crypt/win32cryptmodule.cpp
-+++ b/win32/src/win32crypt/win32cryptmodule.cpp
-@@ -597,34 +597,59 @@ static PyObject *PyCertOpenStore(PyObject *self, PyObject *args, PyObject *kwarg
- 		}
- 	else{
- 		switch((ULONG_PTR)StoreProvider){
-+#if defined(__MINGW32__)
-+			case (ULONG_PTR)14:
-+			case (ULONG_PTR)8:
-+			case (ULONG_PTR)10:
-+			case (ULONG_PTR)13:
-+			case (ULONG_PTR)16:{
-+#else
- 			case CERT_STORE_PROV_PHYSICAL:
- 			case CERT_STORE_PROV_FILENAME:
- 			case CERT_STORE_PROV_SYSTEM:
- 			case CERT_STORE_PROV_SYSTEM_REGISTRY:
- 			case CERT_STORE_PROV_LDAP:{
-+#endif
- 				if (!PyWinObject_AsWCHAR(obpvPara, (WCHAR **)&pvPara))
- 					return NULL;
- 				free_wchar=TRUE;
- 				break;
- 				}
-+#if defined(__MINGW32__)
-+			case (ULONG_PTR)4:{
-+#else
- 			case CERT_STORE_PROV_REG:{
-+#endif
- 				if (!PyWinObject_AsHKEY(obpvPara, (HKEY *)&pvPara))
- 					return NULL;
- 				break;
- 				}
-+#if defined(__MINGW32__)
-+			case (ULONG_PTR)3:{
-+#else
- 			case CERT_STORE_PROV_FILE:{
-+#endif
- 				if (!PyWinObject_AsHANDLE(obpvPara, (HANDLE *)&pvPara))
- 					return NULL;
- 				break;
- 				}
-+#if defined(__MINGW32__)
-+			case (ULONG_PTR)6:
-+			case (ULONG_PTR)5:{
-+#else
- 			case CERT_STORE_PROV_SERIALIZED:
- 			case CERT_STORE_PROV_PKCS7:{
-+#endif
- 				if (!PyWinObject_AsReadBuffer(obpvPara, (void **)&crypt_data_blob.pbData, &crypt_data_blob.cbData))
- 					return NULL;
- 				pvPara=(void *)&crypt_data_blob;
- 				break;
- 				}
-+#if defined(__MINGW32__)
-+			case (ULONG_PTR)2:{
-+#else
- 			case CERT_STORE_PROV_MEMORY:{
-+#endif
- 				// pvPara is not used, warn if something passed in
- 				if (obpvPara != Py_None)
- 					PyErr_Warn(PyExc_RuntimeWarning, "Para ignored for CERT_STORE_PROV_MEMORY");
-diff --git a/win32/src/win32evtlog.i b/win32/src/win32evtlog.i
-index 847230c..142923b 100644
---- a/win32/src/win32evtlog.i
-+++ b/win32/src/win32evtlog.i
-@@ -1012,11 +1012,15 @@ PyCFunction pfnPyEvtUpdateBookmark = (PyCFunction) PyEvtUpdateBookmark;
- 
- PyObject *PyWinObject_FromEVT_VARIANT(PEVT_VARIANT val)
- {
-+#if defined(__MINGW32__)
-+	DWORD val_type = val->Type;
-+#else
- 	if (val->Type & EVT_VARIANT_TYPE_ARRAY){
- 		PyErr_SetString(PyExc_NotImplementedError, "EVT_VARIANT arrays not supported yet");
- 		return NULL;
- 		}
- 	DWORD val_type = val->Type & EVT_VARIANT_TYPE_MASK;
-+#endif
- 	PyObject *obval = NULL;
- 	switch (val_type){
- 		case EvtVarTypeNull:
-diff --git a/win32/src/win32file.i b/win32/src/win32file.i
-index 2b82d37..39e7cd1 100644
---- a/win32/src/win32file.i
-+++ b/win32/src/win32file.i
-@@ -1420,11 +1420,19 @@ static PyObject *PyObject_FromFILE_NOTIFY_INFORMATION(void *buffer, DWORD nbytes
- 	// the filename is exactly 1 byte!  Not clear the best way to
- 	// check this, but this works for now - is it at least the size of
- 	// the *head* of the struct.
-+#if defined(__MINGW32__)
-+	if (nbytes < sizeof(DWORD)*3+2)
-+#else
- 	if (nbytes < sizeof DWORD*3+2)
-+#endif
- 		return ret;
- 	DWORD nbytes_read = 0;
- 	while (1) {
-+#if defined(__MINGW32__)
-+                PyObject *fname = PyWinObject_FromOLECHAR(p->FileName, p->FileNameLength/sizeof(WCHAR));
-+#else
- 		PyObject *fname = PyWinObject_FromOLECHAR(p->FileName, p->FileNameLength/sizeof WCHAR);
-+#endif
- 		if (!fname) {
- 			Py_DECREF(ret);
- 			return NULL;
-diff --git a/win32/src/win32file_comm.cpp b/win32/src/win32file_comm.cpp
-index 19f2eb7..d16fb76 100644
---- a/win32/src/win32file_comm.cpp
-+++ b/win32/src/win32file_comm.cpp
-@@ -173,11 +173,19 @@ PyDCB::~PyDCB(void)
- {
- }
- 
-+#if defined(__MINGW32__)
-+#define GET_BITFIELD_ENTRY(bitfield_name) \
-+	else if (strcmp(name, #bitfield_name)==0) { \
-+		return PyInt_FromLong(pydcb->m_DCB. bitfield_name); \
-+	} \
-+
-+#else
- #define GET_BITFIELD_ENTRY(bitfield_name) \
- 	else if (strcmp(name, #bitfield_name)==0) { \
- 		return PyInt_FromLong(pydcb->m_DCB.##bitfield_name); \
- 	} \
- 
-+#endif
- PyObject *PyDCB::getattro(PyObject *self, PyObject *obname)
- {
- 	PyDCB *pydcb = (PyDCB *)self;
-@@ -204,7 +212,19 @@ PyObject *PyDCB::getattro(PyObject *self, PyObject *obname)
- 	return PyObject_GenericGetAttr(self, obname);
- }
- 
-+#if defined(__MINGW32__)
- #define SET_BITFIELD_ENTRY(bitfield_name) \
-+	else if (strcmp(name, #bitfield_name)==0) { \
-+		if (!PyInt_Check(v)) { \
-+			PyErr_Format(PyExc_TypeError, szNeedIntAttr, #bitfield_name); \
-+			return -1; \
-+		} \
-+		pydcb->m_DCB. bitfield_name = PyInt_AsLong(v); \
-+		return 0; \
-+	} \
-+
-+#else
-+#define SET_BITFIELD_ENTRY(bitfield_name)           \
- 	else if (strcmp(name, #bitfield_name)==0) { \
- 		if (!PyInt_Check(v)) { \
- 			PyErr_Format(PyExc_TypeError, szNeedIntAttr, #bitfield_name); \
-@@ -214,6 +234,7 @@ PyObject *PyDCB::getattro(PyObject *self, PyObject *obname)
- 		return 0; \
- 	} \
- 
-+#endif
- int PyDCB::setattro(PyObject *self, PyObject *obname, PyObject *v)
- {
- 	PyDCB *pydcb = (PyDCB *)self;
-@@ -367,11 +388,19 @@ PyCOMSTAT::~PyCOMSTAT(void)
- }
- 
- #undef GET_BITFIELD_ENTRY
-+#if defined(__MINGW32__)
-+#define GET_BITFIELD_ENTRY(bitfield_name) \
-+	else if (strcmp(name, #bitfield_name)==0) { \
-+		return PyInt_FromLong(pyCOMSTAT->m_COMSTAT. bitfield_name); \
-+	} \
-+
-+#else
- #define GET_BITFIELD_ENTRY(bitfield_name) \
- 	else if (strcmp(name, #bitfield_name)==0) { \
- 		return PyInt_FromLong(pyCOMSTAT->m_COMSTAT.##bitfield_name); \
- 	} \
- 
-+#endif
- PyObject *PyCOMSTAT::getattro(PyObject *self, PyObject *obname)
- {
- 	PyCOMSTAT *pyCOMSTAT = (PyCOMSTAT *)self;
-@@ -392,6 +421,18 @@ PyObject *PyCOMSTAT::getattro(PyObject *self, PyObject *obname)
- }
- 
- #undef SET_BITFIELD_ENTRY
-+#if defined(__MINGW32__)
-+#define SET_BITFIELD_ENTRY(bitfield_name) \
-+	else if (strcmp(name, #bitfield_name)==0) { \
-+		if (!PyInt_Check(v)) { \
-+			PyErr_Format(PyExc_TypeError, szNeedIntAttr, #bitfield_name); \
-+			return -1; \
-+		} \
-+		pyCOMSTAT->m_COMSTAT. bitfield_name = PyInt_AsLong(v); \
-+		return 0; \
-+	} \
-+
-+#else
- #define SET_BITFIELD_ENTRY(bitfield_name) \
- 	else if (strcmp(name, #bitfield_name)==0) { \
- 		if (!PyInt_Check(v)) { \
-@@ -402,6 +443,7 @@ PyObject *PyCOMSTAT::getattro(PyObject *self, PyObject *obname)
- 		return 0; \
- 	} \
- 
-+#endif
- int PyCOMSTAT::setattro(PyObject *self, PyObject *obname, PyObject *v)
- {
- 	PyCOMSTAT *pyCOMSTAT = (PyCOMSTAT *)self;
-diff --git a/win32/src/win32gui.i b/win32/src/win32gui.i
-index 94b738f..bc5e494 100644
---- a/win32/src/win32gui.i
-+++ b/win32/src/win32gui.i
-@@ -34,6 +34,9 @@
- #include "Dbt.h" // device notification
- #include "malloc.h"
- 
-+#if defined(__MINGW32__)
-+#include <algorithm>
-+#endif
- #ifdef MS_WINCE
- #include "winbase.h"
- #define IS_INTRESOURCE(res) (((DWORD)(res) & 0xffff0000) == 0)
-@@ -640,7 +643,11 @@ typedef int UINT;
- // @object TRACKMOUSEEVENT|A tuple of (dwFlags, hwndTrack, dwHoverTime)
- %typemap(python,in) TRACKMOUSEEVENT *INPUT(TRACKMOUSEEVENT e){
- 	PyObject *obhwnd;
-+#if defined(__MINGW32__)
-+	e.cbSize = sizeof(e);
-+#else
- 	e.cbSize = sizeof e;
-+#endif
- 	if (PyTuple_Check($source)) {
- 		if (PyArg_ParseTuple($source, "lOl", &e.dwFlags, &obhwnd, &e.dwHoverTime) == 0) {
- 			return PyErr_Format(PyExc_TypeError, "%s: a TRACKMOUSEEVENT must be a tuple of 3 integers", "$name");
-@@ -1822,7 +1829,11 @@ PyObject *PyFlashWindowEx(PyObject *self, PyObject *args)
- 	PyObject *ret, *obhwnd;
- 	BOOL rc;
- 	FLASHWINFO f;
-+#if defined(__MINGW32__)
-+	f.cbSize = sizeof(f);
-+#else
- 	f.cbSize = sizeof f;
-+#endif
- 	// @pyparm <o PyHANDLE>|hwnd||Handle to a window
- 	// @pyparm int|dwFlags||Combination of win32con.FLASHW_* flags
- 	// @pyparm int|uCount||Nbr of times to flash
-@@ -3802,7 +3813,11 @@ static PyObject *PyExtractIconEx(PyObject *self, PyObject *args)
-     nicons_got = 1;
- #endif
-     // Asking for 1 always says it got 2!?
-+#if defined(__MINGW32__)
-+    nicons = std::min(nicons, nicons_got);
-+#else
-     nicons = min(nicons, nicons_got);
-+#endif
-     objects_large = PyList_New(nicons);
-     if (!objects_large) goto done;
-     objects_small = PyList_New(nicons);
-@@ -4596,29 +4611,49 @@ BOOL GetOpenFileName(OPENFILENAME *INPUT);
- %typemap (python, in) MENUITEMINFO *INPUT (Py_ssize_t target_size){
- 	if (0 != PyObject_AsReadBuffer($source, (const void **)&$target, &target_size))
- 		return NULL;
-+#if defined(__MINGW32__)
-+	if (sizeof(MENUITEMINFO) != target_size)
-+		return PyErr_Format(PyExc_TypeError, "Argument must be a %d-byte string/buffer (got %d bytes)", sizeof(MENUITEMINFO), target_size);
-+#else
- 	if (sizeof MENUITEMINFO != target_size)
- 		return PyErr_Format(PyExc_TypeError, "Argument must be a %d-byte string/buffer (got %d bytes)", sizeof MENUITEMINFO, target_size);
-+#endif
- }
- 
- %typemap (python,in) MENUITEMINFO *BOTH(Py_ssize_t target_size) {
- 	if (0 != PyObject_AsWriteBuffer($source, (void **)&$target, &target_size))
- 		return NULL;
-+#if defined(__MINGW32__)
-+	if (sizeof(MENUITEMINFO) != target_size)
-+		return PyErr_Format(PyExc_TypeError, "Argument must be a %d-byte buffer (got %d bytes)", sizeof(MENUITEMINFO), target_size);
-+#else
- 	if (sizeof MENUITEMINFO != target_size)
- 		return PyErr_Format(PyExc_TypeError, "Argument must be a %d-byte buffer (got %d bytes)", sizeof MENUITEMINFO, target_size);
-+#endif
- }
- 
- %typemap (python, in) MENUINFO *INPUT (Py_ssize_t target_size){
- 	if (0 != PyObject_AsReadBuffer($source, (const void **)&$target, &target_size))
- 		return NULL;
-+#if defined(__MINGW32__)
-+	if (sizeof(MENUINFO) != target_size)
-+		return PyErr_Format(PyExc_TypeError, "Argument must be a %d-byte string/buffer (got %d bytes)", sizeof(MENUINFO), target_size);
-+#else
- 	if (sizeof MENUINFO != target_size)
- 		return PyErr_Format(PyExc_TypeError, "Argument must be a %d-byte string/buffer (got %d bytes)", sizeof MENUINFO, target_size);
-+#endif
- }
- 
- %typemap (python,in) MENUINFO *BOTH(Py_ssize_t target_size) {
- 	if (0 != PyObject_AsWriteBuffer($source, (void **)&$target, &target_size))
- 		return NULL;
-+#if defined(__MINGW32__)
-+	if (sizeof(MENUINFO) != target_size)
-+		return PyErr_Format(PyExc_TypeError, "Argument must be a %d-byte buffer (got %d bytes)", sizeof(MENUINFO), target_size);
-+#else
- 	if (sizeof MENUINFO != target_size)
- 		return PyErr_Format(PyExc_TypeError, "Argument must be a %d-byte buffer (got %d bytes)", sizeof MENUINFO, target_size);
-+#endif
- }
- 
- // @pyswig |InsertMenuItem|Inserts a menu item
-@@ -4750,8 +4785,13 @@ PyObject *PySetMenuInfo(PyObject *self, PyObject *args)
- 
- 	if (0 != PyObject_AsReadBuffer(obInfo, (const void **)&pInfo, &cbInfo))
- 		return NULL;
-+#if defined(__MINGW32__)
-+	if (sizeof(MENUINFO) != cbInfo)
-+		return PyErr_Format(PyExc_TypeError, "Argument must be a %d byte string/buffer (got %d bytes)", sizeof(MENUINFO), cbInfo);
-+#else
- 	if (sizeof MENUINFO != cbInfo)
- 		return PyErr_Format(PyExc_TypeError, "Argument must be a %d byte string/buffer (got %d bytes)", sizeof MENUINFO, cbInfo);
-+#endif
- 
- 	Py_BEGIN_ALLOW_THREADS
- 	result = (*pfnSetMenuInfo)(hmenu, pInfo);
-@@ -4787,8 +4827,13 @@ PyObject *PyGetMenuInfo(PyObject *self, PyObject *args)
- 
- 	if (0 != PyObject_AsWriteBuffer(obInfo, (void **)&pInfo, &cbInfo))
- 		return NULL;
-+#if defined(__MINGW32__)
-+	if (sizeof(MENUINFO) != cbInfo)
-+		return PyErr_Format(PyExc_TypeError, "Argument must be a %d byte buffer (got %d bytes)", sizeof(MENUINFO), cbInfo);
-+#else
- 	if (sizeof MENUINFO != cbInfo)
- 		return PyErr_Format(PyExc_TypeError, "Argument must be a %d byte buffer (got %d bytes)", sizeof MENUINFO, cbInfo);
-+#endif
- 
- 	Py_BEGIN_ALLOW_THREADS
- 	result = (*pfnGetMenuInfo)(hmenu, pInfo);
-@@ -6005,7 +6050,11 @@ PyGetClassName(PyObject *self, PyObject *args)
- 	if (!PyWinObject_AsHANDLE(obhwnd, (HANDLE *)&hwnd))
- 		return NULL;
- 	// dont bother with lock - no callback possible.
-+#if defined(__MINGW32__)
-+	int nchars = GetClassName(hwnd, buf, sizeof(buf)/sizeof(buf[0]));
-+#else
- 	int nchars = GetClassName(hwnd, buf, sizeof buf/sizeof buf[0]);
-+#endif
- 	if (nchars==0)
- 		return PyWin_SetAPIError("GetClassName");
- 	return PyWinObject_FromTCHAR(buf, nchars);
-@@ -6370,7 +6419,11 @@ BOOL PyParse_OPENFILENAMEW_Args(PyObject *args, PyObject *kwargs, OPENFILENAMEW
- 	// lpstrFile buffer receives full path and possibly multiple file names, allocate extra space
- 	if (!PyWinObject_AsWCHAR(obFile, &initfile, TRUE, &initfilechars))
- 		goto done;
-+#if defined(__MINGW32__)
-+	pofn->nMaxFile=std::max(pofn->nMaxFile, initfilechars+1);
-+#else
- 	pofn->nMaxFile=max(pofn->nMaxFile, initfilechars+1);
-+#endif
- 	bufsize=pofn->nMaxFile*sizeof(WCHAR);
- 	pofn->lpstrFile=(LPWSTR)malloc(bufsize);
- 	if (pofn->lpstrFile==NULL){
-@@ -7506,13 +7559,13 @@ PyObject *PyRegisterDeviceNotification(PyObject *self, PyObject *args)
- 				"structure says it has %d bytes, but %d was provided",
- 				(int)struct_bytes, (int)nbytes);
- 	// @pyseeapi RegisterDeviceNotification
--	HDEVNOTIFY not;
-+	HDEVNOTIFY notify;
- 	Py_BEGIN_ALLOW_THREADS
--	not = RegisterDeviceNotification(handle, (void *)filter, flags);
-+	notify = RegisterDeviceNotification(handle, (void *)filter, flags);
- 	Py_END_ALLOW_THREADS
--	if (not == NULL)
-+	if (notify == NULL)
- 		return PyWin_SetAPIError("RegisterDeviceNotification");
--	return PyWinObject_FromHDEVNOTIFY(not);
-+	return PyWinObject_FromHDEVNOTIFY(notify);
- }
- %}
- %native(RegisterDeviceNotification) PyRegisterDeviceNotification;
-diff --git a/win32/src/win32inet.i b/win32/src/win32inet.i
-index 92d7462..16a8912 100644
---- a/win32/src/win32inet.i
-+++ b/win32/src/win32inet.i
-@@ -15,6 +15,9 @@
- %{
- #undef PyHANDLE // undef earlier define, so we are back to the class.
- #include "pywinobjects.h"
-+#if defined(__MINGW32__)
-+#include <algorithm>
-+#endif
- 
- void CALLBACK PyHINTERNET_StatusChange(
- 	HINTERNET hInternet,
-@@ -953,8 +956,10 @@ PyObject *PyInternetQueryOption(PyObject *self, PyObject *args)
- 		case INTERNET_OPTION_RECEIVE_TIMEOUT:	// @flag INTERNET_OPTION_RECEIVE_TIMEOUT|Int - timeout in millseconds
- 												// @flag INTERNET_OPTION_CONTROL_RECEIVE_TIMEOUT|Int - timeout in millseconds
- 		case INTERNET_OPTION_CODEPAGE:		// @flag INTERNET_OPTION_CODEPAGE|Int - Codepage of host part of URL
-+#if !defined(__MINGW32__)
- 		case INTERNET_OPTION_CODEPAGE_PATH:	// @flag INTERNET_OPTION_CODEPAGE_PATH|Int - Codepage for URL
- 		case INTERNET_OPTION_CODEPAGE_EXTRA:	// @flag INTERNET_OPTION_CODEPAGE_EXTRA|Int - Codepage for path part of URL
-+#endif
- 		case INTERNET_OPTION_CONNECT_RETRIES:		// @flag INTERNET_OPTION_CONNECT_RETRIES|Int - Number of time to try to reconnect to host
- 		case INTERNET_OPTION_CONNECT_TIMEOUT:		// @flag INTERNET_OPTION_CONNECT_TIMEOUT|Int - Connection timeout in milliseconds
- 		case INTERNET_OPTION_CONNECTED_STATE:		// @flag INTERNET_OPTION_CONNECTED_STATE|Int - Connection state, INTERNET_STATE_*
-@@ -962,7 +967,9 @@ PyObject *PyInternetQueryOption(PyObject *self, PyObject *args)
- 		case INTERNET_OPTION_ERROR_MASK:		// @flag INTERNET_OPTION_ERROR_MASK|Int, combination of INTERNET_ERROR_MASK_*
- 		case INTERNET_OPTION_EXTENDED_ERROR:		// @flag INTERNET_OPTION_EXTENDED_ERROR|Int, ERROR_INTERNET_*
- 		case INTERNET_OPTION_FROM_CACHE_TIMEOUT:		// @flag INTERNET_OPTION_FROM_CACHE_TIMEOUT|Int - Timeout in ms before cached copy is used
-+#if !defined(__MINGW32__)
- 		case INTERNET_OPTION_IDN:		// @flag INTERNET_OPTION_IDN|Int, INTERNET_FLAG_IDN_*
-+#endif
- 		case INTERNET_OPTION_MAX_CONNS_PER_1_0_SERVER:		// @flag INTERNET_OPTION_MAX_CONNS_PER_1_0_SERVER|Int
- 		case INTERNET_OPTION_MAX_CONNS_PER_SERVER:		// @flag INTERNET_OPTION_MAX_CONNS_PER_SERVER|Int
- 		case INTERNET_OPTION_READ_BUFFER_SIZE:		// @flag INTERNET_OPTION_READ_BUFFER_SIZE|Int
-@@ -974,7 +981,9 @@ PyObject *PyInternetQueryOption(PyObject *self, PyObject *args)
- 			ret=PyLong_FromUnsignedLong(*(unsigned long *)buf);
- 			break;
- 		case INTERNET_OPTION_BYPASS_EDITED_ENTRY:		// @flag INTERNET_OPTION_BYPASS_EDITED_ENTRY|Boolean
-+#if !defined(__MINGW32__)
- 		case INTERNET_OPTION_HTTP_DECODING:		// @flag INTERNET_OPTION_HTTP_DECODING|Boolean
-+#endif
- 		case INTERNET_OPTION_IGNORE_OFFLINE:		// @flag INTERNET_OPTION_IGNORE_OFFLINE|Boolean
- 			ret=PyBool_FromLong(*(BOOL *)buf);
- 			break;
-@@ -1157,14 +1166,18 @@ PyObject *PyInternetSetOption(PyObject *self, PyObject *args)
- 		case INTERNET_OPTION_RECEIVE_TIMEOUT:	// @flag INTERNET_OPTION_RECEIVE_TIMEOUT|Int - timeout in millseconds
- 												// @flag INTERNET_OPTION_CONTROL_RECEIVE_TIMEOUT|Int - timeout in millseconds
- 		case INTERNET_OPTION_CODEPAGE:		// @flag INTERNET_OPTION_CODEPAGE|Int - Codepage of host part of URL
-+#if !defined(__MINGW32__)
- 		case INTERNET_OPTION_CODEPAGE_PATH:	// @flag INTERNET_OPTION_CODEPAGE_PATH|Codepage for URL
- 		case INTERNET_OPTION_CODEPAGE_EXTRA:	// @flag INTERNET_OPTION_CODEPAGE_EXTRA|Int - Codepage for path part of URL
-+#endif
- 		case INTERNET_OPTION_CONNECT_RETRIES:		// @flag INTERNET_OPTION_CONNECT_RETRIES|Int - Number of time to try to reconnect to host
- 		case INTERNET_OPTION_CONNECT_TIMEOUT:		// @flag INTERNET_OPTION_CONNECT_TIMEOUT|Int - Connection timeout in milliseconds
- 		case INTERNET_OPTION_CONNECTED_STATE:		// @flag INTERNET_OPTION_CONNECTED_STATE|Int - Connection state, INTERNET_STATE_*
- 		case INTERNET_OPTION_ERROR_MASK:		// @flag INTERNET_OPTION_ERROR_MASK|Int, combination of INTERNET_ERROR_MASK_*
- 		case INTERNET_OPTION_FROM_CACHE_TIMEOUT:		// @flag INTERNET_OPTION_FROM_CACHE_TIMEOUT|Int - Timeout in ms before cached copy is used
-+#if !defined(__MINGW32__)
- 		case INTERNET_OPTION_IDN:		// @flag INTERNET_OPTION_IDN|Int, INTERNET_FLAG_IDN_*
-+#endif
- 		case INTERNET_OPTION_MAX_CONNS_PER_1_0_SERVER:		// @flag INTERNET_OPTION_MAX_CONNS_PER_1_0_SERVER|Int
- 		case INTERNET_OPTION_MAX_CONNS_PER_SERVER:		// @flag INTERNET_OPTION_MAX_CONNS_PER_SERVER|Int
- 		case INTERNET_OPTION_READ_BUFFER_SIZE:		// @flag INTERNET_OPTION_READ_BUFFER_SIZE|Int
-@@ -1189,7 +1202,9 @@ PyObject *PyInternetSetOption(PyObject *self, PyObject *args)
- 				}
- 			break;
- 		case INTERNET_OPTION_BYPASS_EDITED_ENTRY:	// @flag INTERNET_OPTION_BYPASS_EDITED_ENTRY|Boolean
-+#if !defined(__MINGW32__)
- 		case INTERNET_OPTION_HTTP_DECODING:		// @flag INTERNET_OPTION_HTTP_DECODING|Boolean
-+#endif
- 		case INTERNET_OPTION_IGNORE_OFFLINE:	// @flag INTERNET_OPTION_IGNORE_OFFLINE|Boolean
- 			bufsize=sizeof(BOOL);
- 			buf=malloc(bufsize);
-@@ -1835,7 +1850,11 @@ BOOL PyWinObject_AsINTERNET_CACHE_GROUP_INFO(PyObject *ob, INTERNET_CACHE_GROUP_
- 			}
- 		}
- 	if (bsuccess && GroupName)
-+#if defined(__MINGW32__)
-+		_tcsncpy(GroupInfo->szGroupName, GroupName, std::min(namelen, (DWORD)GROUPNAME_MAX_LENGTH));
-+#else
- 		_tcsncpy(GroupInfo->szGroupName, GroupName, min(namelen, GROUPNAME_MAX_LENGTH));
-+#endif
- 	Py_DECREF(dummy_tuple);
- 	PyWinObject_FreeTCHAR(GroupName);
- 	if (OwnerStorage)
-diff --git a/win32/src/win32net/win32net.h b/win32/src/win32net/win32net.h
-index ae7c690..c961c18 100644
---- a/win32/src/win32net/win32net.h
-+++ b/win32/src/win32net/win32net.h
-@@ -62,15 +62,27 @@ PyObject *PyDoGroupDelMembers(PyObject *self, PyObject *args);
- 
- #if WINVER >= 0x0500
- typedef NET_API_STATUS (NET_API_FUNCTION *NetValidateNamefunc)(LPCWSTR, LPCWSTR, LPCWSTR, LPCWSTR, NETSETUP_NAME_TYPE);
--extern NetValidateNamefunc pfnNetValidateName;
-+extern
-+#if defined(__MINGW32__)
-+"C"
-+#endif
-+NetValidateNamefunc pfnNetValidateName;
- 
- typedef NET_API_STATUS (NET_API_FUNCTION *NetGetJoinInformationfunc)(LPCWSTR, LPWSTR *, PNETSETUP_JOIN_STATUS);
- extern NetGetJoinInformationfunc pfnNetGetJoinInformation;
- 
- typedef NET_API_STATUS (NET_API_FUNCTION *NetValidatePasswordPolicyfunc)(LPCWSTR, LPVOID, NET_VALIDATE_PASSWORD_TYPE, LPVOID, LPVOID *);
--extern NetValidatePasswordPolicyfunc pfnNetValidatePasswordPolicy;
-+extern
-+#if defined(__MINGW32__)
-+"C"
-+#endif
-+NetValidatePasswordPolicyfunc pfnNetValidatePasswordPolicy;
- 
- typedef NET_API_STATUS (NET_API_FUNCTION *NetValidatePasswordPolicyFreefunc)(LPVOID *);
--extern NetValidatePasswordPolicyFreefunc pfnNetValidatePasswordPolicyFree;
-+extern
-+#if defined(__MINGW32__)
-+"C"
-+#endif
-+NetValidatePasswordPolicyFreefunc pfnNetValidatePasswordPolicyFree;
- 
- #endif // WINVER
-diff --git a/win32/src/win32pdhmodule.cpp b/win32/src/win32pdhmodule.cpp
-index 94c4ed1..533dad7 100644
---- a/win32/src/win32pdhmodule.cpp
-+++ b/win32/src/win32pdhmodule.cpp
-@@ -15,6 +15,10 @@ generates Windows .hlp files.
- #include "pdh.h"
- #include "pdhmsg.h"
- 
-+#if defined(__MINGW32__)
-+#include <algorithm>
-+#endif
-+
- /*
- According to MSDN, Pdh calls are thread safe, although there was a bug
- in Win2k that might make it appear to not be.  Plus, the PyW32* macros
-@@ -1013,12 +1017,21 @@ PDH_STATUS __stdcall PyCounterPathCallback(DWORD_PTR dwArg)
- 	return rc;
- }
- 
-+#if defined(__MINGW32__)
-+#define SET_BOOL(r, i) { \
-+	if (i<seqLen){ \
-+		PyObject *subItem = PyTuple_GET_ITEM(flags_tuple, i); \
-+		myCfg.cfg. r = PyObject_IsTrue(subItem); \
-+	} \
-+}
-+#else
- #define SET_BOOL(r, i) { \
- 	if (i<seqLen){ \
- 		PyObject *subItem = PyTuple_GET_ITEM(flags_tuple, i); \
- 		myCfg.cfg.##r = PyObject_IsTrue(subItem); \
- 	} \
- }
-+#endif
- 
- // @pymethod string|win32pdh|BrowseCounters|Displays the counter browsing dialog box so that the user can select the counters to be returned to the caller. 
- static PyObject *PyBrowseCounters(PyObject *self, PyObject *args, PyObject *kwargs)
-@@ -1082,7 +1095,11 @@ static PyObject *PyBrowseCounters(PyObject *self, PyObject *args, PyObject *kwar
- 	// Initialize the return buffer if starting path is passed in. (bInitializePath will also be set)
- 	if (!PyWinObject_AsTCHAR(obInitialPath, &InitialPath, TRUE, &cchInitialPath))
- 		return NULL;	// Last exit without cleanup
-+#if defined(__MINGW32__)
-+	myCfg.cfg.cchReturnPathLength = std::max(cchInitialPath+1, 1024UL);
-+#else
- 	myCfg.cfg.cchReturnPathLength = max(cchInitialPath+1, 1024);
-+#endif
- 	myCfg.cfg.szReturnPathBuffer = (TCHAR *)malloc(myCfg.cfg.cchReturnPathLength * sizeof(TCHAR));
- 	if (myCfg.cfg.szReturnPathBuffer == NULL){
- 		PyErr_NoMemory();
-diff --git a/win32/src/win32service.i b/win32/src/win32service.i
-index 11a4a23..fab8092 100644
---- a/win32/src/win32service.i
-+++ b/win32/src/win32service.i
-@@ -1818,7 +1818,6 @@ PyObject *PyQueryServiceConfig2(PyObject *self, PyObject *args)
- #define SERVICE_CONTROL_HARDWAREPROFILECHANGE SERVICE_CONTROL_HARDWAREPROFILECHANGE
- #define SERVICE_CONTROL_POWEREVENT SERVICE_CONTROL_POWEREVENT
- #define SERVICE_CONTROL_SESSIONCHANGE SERVICE_CONTROL_SESSIONCHANGE
--#define SERVICE_CONTROL_PRESHUTDOWN SERVICE_CONTROL_PRESHUTDOWN
- 
- 
- #define SC_MANAGER_ALL_ACCESS SC_MANAGER_ALL_ACCESS 
-@@ -1875,7 +1874,6 @@ PyObject *PyQueryServiceConfig2(PyObject *self, PyObject *args)
- #define SERVICE_ACCEPT_HARDWAREPROFILECHANGE SERVICE_ACCEPT_HARDWAREPROFILECHANGE
- #define SERVICE_ACCEPT_POWEREVENT SERVICE_ACCEPT_POWEREVENT
- #define SERVICE_ACCEPT_SESSIONCHANGE SERVICE_ACCEPT_SESSIONCHANGE
--#define SERVICE_ACCEPT_PRESHUTDOWN SERVICE_ACCEPT_PRESHUTDOWN
- 
- //#define SERVICE_ERROR_IGNORER_IGNORE SERVICE_ERROR_IGNORER_IGNORE
- #define SERVICE_BOOT_START SERVICE_BOOT_START 
-diff --git a/win32/src/win32trace.cpp b/win32/src/win32trace.cpp
-index 2237094..60e7c83 100644
---- a/win32/src/win32trace.cpp
-+++ b/win32/src/win32trace.cpp
-@@ -35,6 +35,9 @@ See - I told you the implementation was simple :-)
- 
- 
- 
-+#if defined(__MINGW32__)
-+#include <algorithm>
-+#endif
- 
- const unsigned long BUFFER_SIZE = 0x20000; // Includes size integer.
- const TCHAR *MAP_OBJECT_NAME = _T("Global\\PythonTraceOutputMapping");
-@@ -341,7 +344,11 @@ BOOL PyTraceObject::WriteData(const char *data, unsigned len)
-     Py_BEGIN_ALLOW_THREADS
-     const char *data_this = data;
-     while (len) {
-+#if defined(__MINGW32__)
-+        unsigned len_this = std::min(static_cast<unsigned long>(len), BUFFER_SIZE/2);
-+#else
-         unsigned len_this = min(len, BUFFER_SIZE/2);
-+#endif
-         BOOL ok = GetMyMutex();
-         if (ok) {
-             // must use types with identical size on win32 and win64
Index: docker/msys/pywin32git.patch
===================================================================
--- docker/msys/pywin32git.patch	(revision 920)
+++ docker/msys/pywin32git.patch	(revision 920)
@@ -0,0 +1,227 @@
+diff --git a/.github/issue_template.md b/.github/issue_template.md
+new file mode 100644
+index 00000000..9c724696
+--- /dev/null
++++ b/.github/issue_template.md
+@@ -0,0 +1,11 @@
++Note that issues in this repository are only for bugs or feature requests in the pywin32.
++
++**If you need support or help using this package, please follow [these instructions](https://github.com/mhammond/pywin32/blob/master/README.md#support)** - support or help requests will be closed without comment.
++
++For all bugs, please provide the following information.
++
++* Expected behavior and actual behavior.
++
++* Steps to reproduce the problem.
++
++* Version of Python and pywin32
+diff --git a/CHANGES.txt b/CHANGES.txt
+index 4b3fcbe3..d209569c 100644
+--- a/CHANGES.txt
++++ b/CHANGES.txt
+@@ -4,6 +4,10 @@ Generally created by hand after running:
+    hg log -rb2xx: > log.out
+ However contributors are encouraged to add their own entries for their work.
+ 
++Since build 224:
++----------------
++* PythonWin is now able to start with non-English active keyboard layout.
++
+ Since build 223:
+ ----------------
+ * Built with a released version of Python 3.7, which fixes various date related
+diff --git a/Pythonwin/pywin/scintilla/keycodes.py b/Pythonwin/pywin/scintilla/keycodes.py
+index 6b783761..d9021828 100644
+--- a/Pythonwin/pywin/scintilla/keycodes.py
++++ b/Pythonwin/pywin/scintilla/keycodes.py
+@@ -35,7 +35,9 @@ def get_vk(chardesc):
+         # it is a character.
+         info = win32api.VkKeyScan(chardesc)
+         if info==-1:
+-            return None, None
++            # Note: returning None, None causes an error when keyboard layout is non-English, see the report below
++            # https://stackoverflow.com/questions/45138084/pythonwin-occasionally-gives-an-error-on-opening
++            return 0, 0
+         vk = win32api.LOBYTE(info)
+         state = win32api.HIBYTE(info)
+         modifiers = 0
+diff --git a/appveyor.yml b/appveyor.yml
+index a45bdb39..f84cdbc4 100644
+--- a/appveyor.yml
++++ b/appveyor.yml
+@@ -20,6 +20,8 @@ environment:
+       PYTHON_MINOR: 5
+     - PYTHON_MAJOR: 3
+       PYTHON_MINOR: 6
++    - PYTHON_MAJOR: 3
++      PYTHON_MINOR: 7
+ 
+ install:
+   # Prepare environment
+@@ -42,6 +44,7 @@ init:
+   # Following the matrix here: https://wiki.python.org/moin/WindowsCompilers#Which_Microsoft_Visual_C.2B-.2B-_compiler_to_use_with_a_specific_Python_version_.3F
+   - if "%PLATFORM%"=="x86" set VC_ARCH=x86
+   - if "%PLATFORM%"=="x64" set VC_ARCH=amd64
++  - if "%PYTHON_MAJOR%"=="3" if "%PYTHON_MINOR%"=="7" set VC_VERSION=14.0
+   - if "%PYTHON_MAJOR%"=="3" if "%PYTHON_MINOR%"=="6" set VC_VERSION=14.0
+   - if "%PYTHON_MAJOR%"=="3" if "%PYTHON_MINOR%"=="5" set VC_VERSION=14.0
+   - if "%PYTHON_MAJOR%"=="3" if "%PYTHON_MINOR%"=="4" set VC_VERSION=10.0
+diff --git a/setup.py b/setup.py
+index 8c397e1e..7c35d909 100644
+--- a/setup.py
++++ b/setup.py
+@@ -1883,6 +1883,7 @@ com_extensions += [
+                     depends=["%(internet)s/internet_pch.h" % dirs]),
+     WinExt_win32com('mapi', libraries="advapi32", pch_header="PythonCOM.h",
+                     include_dirs=["%(mapi)s/mapi_headers" % dirs],
++                    optional_headers=['edkmdb.h', 'edkguid.h'],
+                     sources=("""
+                         %(mapi)s/mapi.i                 %(mapi)s/mapi.cpp
+                         %(mapi)s/PyIABContainer.i       %(mapi)s/PyIABContainer.cpp
+@@ -1911,6 +1912,7 @@ com_extensions += [
+                         """ % dirs).split()),
+     WinExt_win32com_mapi('exchange', libraries="advapi32",
+                          include_dirs=["%(mapi)s/mapi_headers" % dirs],
++                         optional_headers=['edkmdb.h', 'edkguid.h'],
+                          sources=("""
+                                   %(mapi)s/exchange.i         %(mapi)s/exchange.cpp
+                                   %(mapi)s/PyIExchangeManageStore.i %(mapi)s/PyIExchangeManageStore.cpp
+@@ -2438,6 +2440,17 @@ cmdclass = { 'install': my_install,
+              'build_scripts' : my_build_scripts,
+            }
+ 
++classifiers = [ 'Environment :: Win32 (MS Windows)',
++	            'Intended Audience :: Developers',
++	            'License :: OSI Approved :: Python Software Foundation License',
++	            'Operating System :: Microsoft :: Windows',
++	            'Programming Language :: Python :: 2.7',
++	            'Programming Language :: Python :: 3.5',
++	            'Programming Language :: Python :: 3.6',
++	            'Programming Language :: Python :: 3.7',
++	            'Programming Language :: Python :: Implementation :: CPython',
++	          ]
++
+ dist = setup(name="pywin32",
+       version=str(build_id),
+       description="Python for Window Extensions",
+@@ -2449,6 +2462,7 @@ dist = setup(name="pywin32",
+       author_email = "mhammond@skippinet.com.au",
+       url="https://github.com/mhammond/pywin32",
+       license="PSF",
++      classifiers = classifiers,
+       cmdclass = cmdclass,
+       options = {"bdist_wininst":
+                     {"install_script": "pywin32_postinstall.py",
+diff --git a/win32/Lib/win32con.py b/win32/Lib/win32con.py
+index a37967f7..eb6b8a90 100644
+--- a/win32/Lib/win32con.py
++++ b/win32/Lib/win32con.py
+@@ -2060,6 +2060,9 @@ PROCESS_CREATE_PROCESS = (128)
+ PROCESS_SET_QUOTA = (256)
+ PROCESS_SET_INFORMATION = (512)
+ PROCESS_QUERY_INFORMATION = (1024)
++PROCESS_SUSPEND_RESUME = (2048)
++PROCESS_QUERY_LIMITED_INFORMATION = (4096)
++PROCESS_SET_LIMITED_INFORMATION = (8192)
+ PROCESS_ALL_ACCESS = (STANDARD_RIGHTS_REQUIRED | SYNCHRONIZE | 4095)
+ THREAD_TERMINATE = (1)
+ THREAD_SUSPEND_RESUME = (2)
+@@ -2070,6 +2073,9 @@ THREAD_QUERY_INFORMATION = (64)
+ THREAD_SET_THREAD_TOKEN = (128)
+ THREAD_IMPERSONATE = (256)
+ THREAD_DIRECT_IMPERSONATION = (512)
++THREAD_SET_LIMITED_INFORMATION = (1024)
++THREAD_QUERY_LIMITED_INFORMATION = (2048)
++THREAD_RESUME = (4096)
+ TLS_MINIMUM_AVAILABLE = 64
+ EVENT_MODIFY_STATE = 2
+ MUTANT_QUERY_STATE = 1
+diff --git a/win32/Lib/win32timezone.py b/win32/Lib/win32timezone.py
+index 83a119dc..6d65af7d 100644
+--- a/win32/Lib/win32timezone.py
++++ b/win32/Lib/win32timezone.py
+@@ -715,14 +715,22 @@ class TimeZoneInfo(datetime.tzinfo):
+ 	@staticmethod
+ 	def _get_indexed_time_zone_keys(index_key='Index'):
+ 		"""
+-		Get the names of the registry keys indexed by a value in that key.
++		Get the names of the registry keys indexed by a value in that key,
++		ignoring any keys for which that value is empty or missing.
+ 		"""
+ 		key_names = list(TimeZoneInfo._get_time_zone_key_names())
++
+ 		def get_index_value(key_name):
+ 			key = TimeZoneInfo._get_time_zone_key(key_name)
+-			return key[index_key]
++			return key.get(index_key)
++
+ 		values = map(get_index_value, key_names)
+-		return zip(values, key_names)
++
++		return (
++			(value, key_name)
++			for value, key_name in zip(values, key_names)
++			if value
++		)
+ 
+ 	@staticmethod
+ 	def get_sorted_time_zone_names():
+@@ -786,25 +794,6 @@ class _RegKeyDict(dict):
+ 		except WindowsError: pass
+ 
+ 
+-# for backward compatibility
+-def deprecated(func, name='Unknown'):
+-	"""This is a decorator which can be used to mark functions
+-	as deprecated. It will result in a warning being emmitted
+-	when the function is used."""
+-	def newFunc(*args, **kwargs):
+-		warnings.warn("Call to deprecated function %s." % name,
+-			category=DeprecationWarning)
+-		return func(*args, **kwargs)
+-	newFunc.__name__ = func.__name__
+-	newFunc.__doc__ = func.__doc__
+-	newFunc.__dict__.update(func.__dict__)
+-	return newFunc
+-
+-GetTimeZoneNames = deprecated(TimeZoneInfo._get_time_zone_key_names, 'GetTimeZoneNames')
+-GetIndexedTimeZoneNames = deprecated(TimeZoneInfo._get_indexed_time_zone_keys, 'GetIndexedTimeZoneNames')
+-GetSortedTimeZoneNames = deprecated(TimeZoneInfo.get_sorted_time_zone_names, 'GetSortedTimeZoneNames')
+-# end backward compatibility
+-
+ def utcnow():
+ 	"""
+ 	Return the UTC time now with timezone awareness as enabled
+@@ -860,7 +849,7 @@ def resolveMUITimeZone(spec):
+ 	spec should be of the format @path,-stringID[;comment]
+ 	see http://msdn2.microsoft.com/en-us/library/ms725481.aspx for details
+ 	"""
+-	pattern = re.compile('@(?P<dllname>.*),-(?P<index>\d+)(?:;(?P<comment>.*))?')
++	pattern = re.compile(r'@(?P<dllname>.*),-(?P<index>\d+)(?:;(?P<comment>.*))?')
+ 	matcher = pattern.match(spec)
+ 	assert matcher, 'Could not parse MUI spec'
+ 
+diff --git a/win32/Lib/winnt.py b/win32/Lib/winnt.py
+index 15584efa..021a32b1 100644
+--- a/win32/Lib/winnt.py
++++ b/win32/Lib/winnt.py
+@@ -194,6 +194,9 @@ PROCESS_CREATE_PROCESS = (128)
+ PROCESS_SET_QUOTA = (256)
+ PROCESS_SET_INFORMATION = (512)
+ PROCESS_QUERY_INFORMATION = (1024)
++PROCESS_SUSPEND_RESUME = (2048)
++PROCESS_QUERY_LIMITED_INFORMATION = (4096)
++PROCESS_SET_LIMITED_INFORMATION = (8192)
+ MAXIMUM_PROCESSORS = 32
+ THREAD_TERMINATE = (1)
+ THREAD_SUSPEND_RESUME = (2)
+@@ -204,6 +207,9 @@ THREAD_QUERY_INFORMATION = (64)
+ THREAD_SET_THREAD_TOKEN = (128)
+ THREAD_IMPERSONATE = (256)
+ THREAD_DIRECT_IMPERSONATION = (512)
++THREAD_SET_LIMITED_INFORMATION = (1024)
++THREAD_QUERY_LIMITED_INFORMATION = (2048)
++THREAD_RESUME = (4096)
+ JOB_OBJECT_ASSIGN_PROCESS = (1)
+ JOB_OBJECT_SET_ATTRIBUTES = (2)
+ JOB_OBJECT_QUERY = (4)
Index: docker/msys/pywin32git.patch
===================================================================
--- docker/msys/pywin32git.patch	(revision 920)
+++ 	(revision )
@@ -1,227 +1,0 @@
-diff --git a/.github/issue_template.md b/.github/issue_template.md
-new file mode 100644
-index 00000000..9c724696
---- /dev/null
-+++ b/.github/issue_template.md
-@@ -0,0 +1,11 @@
-+Note that issues in this repository are only for bugs or feature requests in the pywin32.
-+
-+**If you need support or help using this package, please follow [these instructions](https://github.com/mhammond/pywin32/blob/master/README.md#support)** - support or help requests will be closed without comment.
-+
-+For all bugs, please provide the following information.
-+
-+* Expected behavior and actual behavior.
-+
-+* Steps to reproduce the problem.
-+
-+* Version of Python and pywin32
-diff --git a/CHANGES.txt b/CHANGES.txt
-index 4b3fcbe3..d209569c 100644
---- a/CHANGES.txt
-+++ b/CHANGES.txt
-@@ -4,6 +4,10 @@ Generally created by hand after running:
-    hg log -rb2xx: > log.out
- However contributors are encouraged to add their own entries for their work.
- 
-+Since build 224:
-+----------------
-+* PythonWin is now able to start with non-English active keyboard layout.
-+
- Since build 223:
- ----------------
- * Built with a released version of Python 3.7, which fixes various date related
-diff --git a/Pythonwin/pywin/scintilla/keycodes.py b/Pythonwin/pywin/scintilla/keycodes.py
-index 6b783761..d9021828 100644
---- a/Pythonwin/pywin/scintilla/keycodes.py
-+++ b/Pythonwin/pywin/scintilla/keycodes.py
-@@ -35,7 +35,9 @@ def get_vk(chardesc):
-         # it is a character.
-         info = win32api.VkKeyScan(chardesc)
-         if info==-1:
--            return None, None
-+            # Note: returning None, None causes an error when keyboard layout is non-English, see the report below
-+            # https://stackoverflow.com/questions/45138084/pythonwin-occasionally-gives-an-error-on-opening
-+            return 0, 0
-         vk = win32api.LOBYTE(info)
-         state = win32api.HIBYTE(info)
-         modifiers = 0
-diff --git a/appveyor.yml b/appveyor.yml
-index a45bdb39..f84cdbc4 100644
---- a/appveyor.yml
-+++ b/appveyor.yml
-@@ -20,6 +20,8 @@ environment:
-       PYTHON_MINOR: 5
-     - PYTHON_MAJOR: 3
-       PYTHON_MINOR: 6
-+    - PYTHON_MAJOR: 3
-+      PYTHON_MINOR: 7
- 
- install:
-   # Prepare environment
-@@ -42,6 +44,7 @@ init:
-   # Following the matrix here: https://wiki.python.org/moin/WindowsCompilers#Which_Microsoft_Visual_C.2B-.2B-_compiler_to_use_with_a_specific_Python_version_.3F
-   - if "%PLATFORM%"=="x86" set VC_ARCH=x86
-   - if "%PLATFORM%"=="x64" set VC_ARCH=amd64
-+  - if "%PYTHON_MAJOR%"=="3" if "%PYTHON_MINOR%"=="7" set VC_VERSION=14.0
-   - if "%PYTHON_MAJOR%"=="3" if "%PYTHON_MINOR%"=="6" set VC_VERSION=14.0
-   - if "%PYTHON_MAJOR%"=="3" if "%PYTHON_MINOR%"=="5" set VC_VERSION=14.0
-   - if "%PYTHON_MAJOR%"=="3" if "%PYTHON_MINOR%"=="4" set VC_VERSION=10.0
-diff --git a/setup.py b/setup.py
-index 8c397e1e..7c35d909 100644
---- a/setup.py
-+++ b/setup.py
-@@ -1883,6 +1883,7 @@ com_extensions += [
-                     depends=["%(internet)s/internet_pch.h" % dirs]),
-     WinExt_win32com('mapi', libraries="advapi32", pch_header="PythonCOM.h",
-                     include_dirs=["%(mapi)s/mapi_headers" % dirs],
-+                    optional_headers=['edkmdb.h', 'edkguid.h'],
-                     sources=("""
-                         %(mapi)s/mapi.i                 %(mapi)s/mapi.cpp
-                         %(mapi)s/PyIABContainer.i       %(mapi)s/PyIABContainer.cpp
-@@ -1911,6 +1912,7 @@ com_extensions += [
-                         """ % dirs).split()),
-     WinExt_win32com_mapi('exchange', libraries="advapi32",
-                          include_dirs=["%(mapi)s/mapi_headers" % dirs],
-+                         optional_headers=['edkmdb.h', 'edkguid.h'],
-                          sources=("""
-                                   %(mapi)s/exchange.i         %(mapi)s/exchange.cpp
-                                   %(mapi)s/PyIExchangeManageStore.i %(mapi)s/PyIExchangeManageStore.cpp
-@@ -2438,6 +2440,17 @@ cmdclass = { 'install': my_install,
-              'build_scripts' : my_build_scripts,
-            }
- 
-+classifiers = [ 'Environment :: Win32 (MS Windows)',
-+	            'Intended Audience :: Developers',
-+	            'License :: OSI Approved :: Python Software Foundation License',
-+	            'Operating System :: Microsoft :: Windows',
-+	            'Programming Language :: Python :: 2.7',
-+	            'Programming Language :: Python :: 3.5',
-+	            'Programming Language :: Python :: 3.6',
-+	            'Programming Language :: Python :: 3.7',
-+	            'Programming Language :: Python :: Implementation :: CPython',
-+	          ]
-+
- dist = setup(name="pywin32",
-       version=str(build_id),
-       description="Python for Window Extensions",
-@@ -2449,6 +2462,7 @@ dist = setup(name="pywin32",
-       author_email = "mhammond@skippinet.com.au",
-       url="https://github.com/mhammond/pywin32",
-       license="PSF",
-+      classifiers = classifiers,
-       cmdclass = cmdclass,
-       options = {"bdist_wininst":
-                     {"install_script": "pywin32_postinstall.py",
-diff --git a/win32/Lib/win32con.py b/win32/Lib/win32con.py
-index a37967f7..eb6b8a90 100644
---- a/win32/Lib/win32con.py
-+++ b/win32/Lib/win32con.py
-@@ -2060,6 +2060,9 @@ PROCESS_CREATE_PROCESS = (128)
- PROCESS_SET_QUOTA = (256)
- PROCESS_SET_INFORMATION = (512)
- PROCESS_QUERY_INFORMATION = (1024)
-+PROCESS_SUSPEND_RESUME = (2048)
-+PROCESS_QUERY_LIMITED_INFORMATION = (4096)
-+PROCESS_SET_LIMITED_INFORMATION = (8192)
- PROCESS_ALL_ACCESS = (STANDARD_RIGHTS_REQUIRED | SYNCHRONIZE | 4095)
- THREAD_TERMINATE = (1)
- THREAD_SUSPEND_RESUME = (2)
-@@ -2070,6 +2073,9 @@ THREAD_QUERY_INFORMATION = (64)
- THREAD_SET_THREAD_TOKEN = (128)
- THREAD_IMPERSONATE = (256)
- THREAD_DIRECT_IMPERSONATION = (512)
-+THREAD_SET_LIMITED_INFORMATION = (1024)
-+THREAD_QUERY_LIMITED_INFORMATION = (2048)
-+THREAD_RESUME = (4096)
- TLS_MINIMUM_AVAILABLE = 64
- EVENT_MODIFY_STATE = 2
- MUTANT_QUERY_STATE = 1
-diff --git a/win32/Lib/win32timezone.py b/win32/Lib/win32timezone.py
-index 83a119dc..6d65af7d 100644
---- a/win32/Lib/win32timezone.py
-+++ b/win32/Lib/win32timezone.py
-@@ -715,14 +715,22 @@ class TimeZoneInfo(datetime.tzinfo):
- 	@staticmethod
- 	def _get_indexed_time_zone_keys(index_key='Index'):
- 		"""
--		Get the names of the registry keys indexed by a value in that key.
-+		Get the names of the registry keys indexed by a value in that key,
-+		ignoring any keys for which that value is empty or missing.
- 		"""
- 		key_names = list(TimeZoneInfo._get_time_zone_key_names())
-+
- 		def get_index_value(key_name):
- 			key = TimeZoneInfo._get_time_zone_key(key_name)
--			return key[index_key]
-+			return key.get(index_key)
-+
- 		values = map(get_index_value, key_names)
--		return zip(values, key_names)
-+
-+		return (
-+			(value, key_name)
-+			for value, key_name in zip(values, key_names)
-+			if value
-+		)
- 
- 	@staticmethod
- 	def get_sorted_time_zone_names():
-@@ -786,25 +794,6 @@ class _RegKeyDict(dict):
- 		except WindowsError: pass
- 
- 
--# for backward compatibility
--def deprecated(func, name='Unknown'):
--	"""This is a decorator which can be used to mark functions
--	as deprecated. It will result in a warning being emmitted
--	when the function is used."""
--	def newFunc(*args, **kwargs):
--		warnings.warn("Call to deprecated function %s." % name,
--			category=DeprecationWarning)
--		return func(*args, **kwargs)
--	newFunc.__name__ = func.__name__
--	newFunc.__doc__ = func.__doc__
--	newFunc.__dict__.update(func.__dict__)
--	return newFunc
--
--GetTimeZoneNames = deprecated(TimeZoneInfo._get_time_zone_key_names, 'GetTimeZoneNames')
--GetIndexedTimeZoneNames = deprecated(TimeZoneInfo._get_indexed_time_zone_keys, 'GetIndexedTimeZoneNames')
--GetSortedTimeZoneNames = deprecated(TimeZoneInfo.get_sorted_time_zone_names, 'GetSortedTimeZoneNames')
--# end backward compatibility
--
- def utcnow():
- 	"""
- 	Return the UTC time now with timezone awareness as enabled
-@@ -860,7 +849,7 @@ def resolveMUITimeZone(spec):
- 	spec should be of the format @path,-stringID[;comment]
- 	see http://msdn2.microsoft.com/en-us/library/ms725481.aspx for details
- 	"""
--	pattern = re.compile('@(?P<dllname>.*),-(?P<index>\d+)(?:;(?P<comment>.*))?')
-+	pattern = re.compile(r'@(?P<dllname>.*),-(?P<index>\d+)(?:;(?P<comment>.*))?')
- 	matcher = pattern.match(spec)
- 	assert matcher, 'Could not parse MUI spec'
- 
-diff --git a/win32/Lib/winnt.py b/win32/Lib/winnt.py
-index 15584efa..021a32b1 100644
---- a/win32/Lib/winnt.py
-+++ b/win32/Lib/winnt.py
-@@ -194,6 +194,9 @@ PROCESS_CREATE_PROCESS = (128)
- PROCESS_SET_QUOTA = (256)
- PROCESS_SET_INFORMATION = (512)
- PROCESS_QUERY_INFORMATION = (1024)
-+PROCESS_SUSPEND_RESUME = (2048)
-+PROCESS_QUERY_LIMITED_INFORMATION = (4096)
-+PROCESS_SET_LIMITED_INFORMATION = (8192)
- MAXIMUM_PROCESSORS = 32
- THREAD_TERMINATE = (1)
- THREAD_SUSPEND_RESUME = (2)
-@@ -204,6 +207,9 @@ THREAD_QUERY_INFORMATION = (64)
- THREAD_SET_THREAD_TOKEN = (128)
- THREAD_IMPERSONATE = (256)
- THREAD_DIRECT_IMPERSONATION = (512)
-+THREAD_SET_LIMITED_INFORMATION = (1024)
-+THREAD_QUERY_LIMITED_INFORMATION = (2048)
-+THREAD_RESUME = (4096)
- JOB_OBJECT_ASSIGN_PROCESS = (1)
- JOB_OBJECT_SET_ATTRIBUTES = (2)
- JOB_OBJECT_QUERY = (4)
Index: docker/msys/setup.sh
===================================================================
--- docker/msys/setup.sh	(revision 920)
+++ docker/msys/setup.sh	(revision 920)
@@ -0,0 +1,69 @@
+#!/bin/bash
+
+set -e -u
+
+pacman -S --noconfirm mc patch unzip mingw-w64-i686-python3 mingw-w64-i686-python3-setuptools mingw-w64-i686-gcc  mingw-w64-i686-gtk3 mingw-w64-i686-python3-lxml mingw-w64-i686-cmake mingw-w64-i686-make mingw-w64-i686-python3-pip mingw-w64-i686-python3-pillow mingw-w64-i686-python3-gobject mingw-w64-i686-python3-cffi
+pacman -Scc --noconfirm
+
+pip3 install jsonrpclib-pelix
+
+echo "Building PyWin32"
+
+cd /build
+
+wget -O - https://github.com/mhammond/pywin32/archive/b224.tar.gz | gzip -dc | tar xf -
+cd pywin32-b224
+patch -p1 < ../pywin32git.patch
+patch -p1 < ../pywin32.patch
+python3 setup.py build
+python3 setup.py install
+
+echo "Building CEFPython"
+
+cd /build
+
+wget -O - http://opensource.spotify.com/cefbuilds/cef_binary_3.3359.1774.gd49d25f_windows32.tar.bz2 | bzip2 -dc | tar xf -
+cd cef_binary_3.3359.1774.gd49d25f_windows32
+
+patch -p1 < ../cef_binary_3.3359.1774.gd49d25f_windows32.patch
+mv tests tests.orig
+
+mkdir build
+cd build
+/usr/bin/env PATH=/mingw32/bin:/usr/local/bin::/c/Windows/System32:/c/Windows:/c/Windows/System32/Wbem:/c/Windows/System32/WindowsPowerShell/v1.0 cmake  -G "MinGW Makefiles" ..
+cd libcef_dll_wrapper
+mingw32-make
+
+cd /build
+
+wget -O - https://github.com/cztomczak/cefpython/archive/v66.0.tar.gz | gzip -dc | tar xf -
+cd cefpython-66.0
+
+patch -p1 < ../cefpython-66.0.patch
+
+mkdir -p build
+cd build
+
+wget https://github.com/cztomczak/cefpython/releases/download/v66-upstream/cef66_3.3359.1774.gd49d25f_win32.zip
+unzip cef66_3.3359.1774.gd49d25f_win32.zip
+rm cef66_3.3359.1774.gd49d25f_win32.zip
+
+cp /build/cef_binary_3.3359.1774.gd49d25f_windows32/build/libcef_dll_wrapper/libcef_dll_wrapper.a cef66_3.3359.1774.gd49d25f_win32/lib
+
+pip3 install -r ../tools/requirements.txt
+
+python3 ../tools/build.py --no-run-tests --no-run-examples 66.0  || true
+python3 ../tools/build.py --no-run-tests --no-run-examples 66.0
+
+echo "Building Py2EXE"
+
+cd /build
+
+wget -O - https://github.com/albertosottile/py2exe/archive/v0.9.3.0.tar.gz | gzip -dc | tar xf -
+cd py2exe-0.9.3.0
+patch -p1 < ../py2exe.patch
+python3 setup.py build
+python3 setup.py install
+
+cd /
+rm -rf /build
Index: docker/msys/setup.sh
===================================================================
--- docker/msys/setup.sh	(revision 920)
+++ 	(revision )
@@ -1,69 +1,0 @@
-#!/bin/bash
-
-set -e -u
-
-pacman -S --noconfirm mc patch unzip mingw-w64-i686-python3 mingw-w64-i686-python3-setuptools mingw-w64-i686-gcc  mingw-w64-i686-gtk3 mingw-w64-i686-python3-lxml mingw-w64-i686-cmake mingw-w64-i686-make mingw-w64-i686-python3-pip mingw-w64-i686-python3-pillow mingw-w64-i686-python3-gobject mingw-w64-i686-python3-cffi
-pacman -Scc --noconfirm
-
-pip3 install jsonrpclib-pelix
-
-echo "Building PyWin32"
-
-cd /build
-
-wget -O - https://github.com/mhammond/pywin32/archive/b224.tar.gz | gzip -dc | tar xf -
-cd pywin32-b224
-patch -p1 < ../pywin32git.patch
-patch -p1 < ../pywin32.patch
-python3 setup.py build
-python3 setup.py install
-
-echo "Building CEFPython"
-
-cd /build
-
-wget -O - http://opensource.spotify.com/cefbuilds/cef_binary_3.3359.1774.gd49d25f_windows32.tar.bz2 | bzip2 -dc | tar xf -
-cd cef_binary_3.3359.1774.gd49d25f_windows32
-
-patch -p1 < ../cef_binary_3.3359.1774.gd49d25f_windows32.patch
-mv tests tests.orig
-
-mkdir build
-cd build
-/usr/bin/env PATH=/mingw32/bin:/usr/local/bin::/c/Windows/System32:/c/Windows:/c/Windows/System32/Wbem:/c/Windows/System32/WindowsPowerShell/v1.0 cmake  -G "MinGW Makefiles" ..
-cd libcef_dll_wrapper
-mingw32-make
-
-cd /build
-
-wget -O - https://github.com/cztomczak/cefpython/archive/v66.0.tar.gz | gzip -dc | tar xf -
-cd cefpython-66.0
-
-patch -p1 < ../cefpython-66.0.patch
-
-mkdir -p build
-cd build
-
-wget https://github.com/cztomczak/cefpython/releases/download/v66-upstream/cef66_3.3359.1774.gd49d25f_win32.zip
-unzip cef66_3.3359.1774.gd49d25f_win32.zip
-rm cef66_3.3359.1774.gd49d25f_win32.zip
-
-cp /build/cef_binary_3.3359.1774.gd49d25f_windows32/build/libcef_dll_wrapper/libcef_dll_wrapper.a cef66_3.3359.1774.gd49d25f_win32/lib
-
-pip3 install -r ../tools/requirements.txt
-
-python3 ../tools/build.py --no-run-tests --no-run-examples 66.0  || true
-python3 ../tools/build.py --no-run-tests --no-run-examples 66.0
-
-echo "Building Py2EXE"
-
-cd /build
-
-wget -O - https://github.com/albertosottile/py2exe/archive/v0.9.3.0.tar.gz | gzip -dc | tar xf -
-cd py2exe-0.9.3.0
-patch -p1 < ../py2exe.patch
-python3 setup.py build
-python3 setup.py install
-
-cd /
-rm -rf /build
