Python: make setup work as expected
diff --git a/bindings/python/.gitignore b/bindings/python/.gitignore
index 31c196e..0ca6529 100644
--- a/bindings/python/.gitignore
+++ b/bindings/python/.gitignore
@@ -1,3 +1,5 @@
 MANIFEST
 dist/
-src/
\ No newline at end of file
+src/
+capstone/lib
+capstone/include
diff --git a/bindings/python/MANIFEST.in b/bindings/python/MANIFEST.in
index 0be11e6..a8834fe 100644
--- a/bindings/python/MANIFEST.in
+++ b/bindings/python/MANIFEST.in
@@ -1,5 +1,3 @@
-recursive-include capstone *
 recursive-include src *
-recursive-include prebuilt *
 include LICENSE.TXT
 include README
diff --git a/bindings/python/Makefile b/bindings/python/Makefile
index ca4ebf8..e3a559c 100644
--- a/bindings/python/Makefile
+++ b/bindings/python/Makefile
@@ -1,8 +1,4 @@
-ifndef BUILDDIR
-OBJDIR = build
-else
-OBJDIR = $(abspath $(BUILDDIR))/obj/bindings/python
-endif
+PYX_BUILDDIR=build_pyx
 
 .PHONY: gen_const install install3 install_cython clean
 
@@ -10,81 +6,53 @@
 	cd .. && python const_generator.py python
 
 install:
-	rm -rf $(OBJDIR) src/
+	rm -rf src/
 	rm -rf prebuilt/win64/capstone.dll
 	rm -rf prebuilt/win32/capstone.dll
 	if test -n "${DESTDIR}"; then \
-		python setup.py build -b $(OBJDIR) install --root="${DESTDIR}"; \
+		python setup.py build install --root="${DESTDIR}"; \
 	else \
-		python setup.py build -b $(OBJDIR) install; \
+		python setup.py build install; \
 	fi
 
 install3:
-	rm -rf $(OBJDIR) src/
+	rm -rf src/
 	rm -rf prebuilt/win64/capstone.dll
 	rm -rf prebuilt/win32/capstone.dll
 	if test -n "${DESTDIR}"; then \
-		python3 setup.py build -b $(OBJDIR) install --root="${DESTDIR}"; \
+		python3 setup.py build install --root="${DESTDIR}"; \
 	else \
-		python3 setup.py build -b $(OBJDIR) install; \
+		python3 setup.py build install; \
 	fi
 
 # NOTE: Newer cython can be installed by: sudo pip install --upgrade cython
 install_cython:
-	rm -rf $(OBJDIR) src/ dist/
+	rm -rf src/ dist/
 	rm -rf prebuilt/win64/capstone.dll
 	rm -rf prebuilt/win32/capstone.dll
-	mkdir -p $(OBJDIR)/pyx
-	cp setup_cython.py $(OBJDIR)
-	cp pyx/ccapstone* $(OBJDIR)/pyx/
-	cp capstone/__init__.py $(OBJDIR)/pyx/__init__.py
-	cp capstone/arm.py $(OBJDIR)/pyx/arm.pyx
-	cp capstone/arm_const.py $(OBJDIR)/pyx/arm_const.pyx
-	cp capstone/arm64.py $(OBJDIR)/pyx/arm64.pyx
-	cp capstone/arm64_const.py $(OBJDIR)/pyx/arm64_const.pyx
-	cp capstone/m68k.py $(OBJDIR)/pyx/m68k.pyx
-	cp capstone/m68k_const.py $(OBJDIR)/pyx/m68k_const.pyx
-	cp capstone/mips.py $(OBJDIR)/pyx/mips.pyx
-	cp capstone/mips_const.py $(OBJDIR)/pyx/mips_const.pyx
-	cp capstone/ppc.py $(OBJDIR)/pyx/ppc.pyx
-	cp capstone/ppc_const.py $(OBJDIR)/pyx/ppc_const.pyx
-	cp capstone/sparc.py $(OBJDIR)/pyx/sparc.pyx
-	cp capstone/sparc_const.py $(OBJDIR)/pyx/sparc_const.pyx
-	cp capstone/systemz.py $(OBJDIR)/pyx/systemz.pyx
-	cp capstone/sysz_const.py $(OBJDIR)/pyx/sysz_const.pyx
-	cp capstone/x86.py $(OBJDIR)/pyx/x86.pyx
-	cp capstone/x86_const.py $(OBJDIR)/pyx/x86_const.pyx
-	cp capstone/xcore.py $(OBJDIR)/pyx/xcore.pyx
-	cp capstone/xcore_const.py $(OBJDIR)/pyx/xcore_const.pyx
-	cd $(OBJDIR) && python setup_cython.py build -b ./tmp install --home=$(OBJDIR)
-	mv $(OBJDIR)/build/lib/python/capstone/* capstone
-	cd $(OBJDIR) && python setup_cython.py build -b ./tmp install
-
-build_cython:
-	rm -rf $(OBJDIR) src/ dist/
-	mkdir -p $(OBJDIR)/pyx
-	cp setup_cython.py $(OBJDIR)
-	cp pyx/ccapstone* $(OBJDIR)/pyx/
-	cp capstone/__init__.py $(OBJDIR)/pyx/__init__.py
-	cp capstone/arm.py $(OBJDIR)/pyx/arm.pyx
-	cp capstone/arm_const.py $(OBJDIR)/pyx/arm_const.pyx
-	cp capstone/arm64.py $(OBJDIR)/pyx/arm64.pyx
-	cp capstone/arm64_const.py $(OBJDIR)/pyx/arm64_const.pyx
-	cp capstone/m68k.py $(OBJDIR)/pyx/m68k.pyx
-	cp capstone/m68k_const.py $(OBJDIR)/pyx/m68k_const.pyx
-	cp capstone/mips.py $(OBJDIR)/pyx/mips.pyx
-	cp capstone/mips_const.py $(OBJDIR)/pyx/mips_const.pyx
-	cp capstone/ppc.py $(OBJDIR)/pyx/ppc.pyx
-	cp capstone/ppc_const.py $(OBJDIR)/pyx/ppc_const.pyx
-	cp capstone/sparc.py $(OBJDIR)/pyx/sparc.pyx
-	cp capstone/sparc_const.py $(OBJDIR)/pyx/sparc_const.pyx
-	cp capstone/systemz.py $(OBJDIR)/pyx/systemz.pyx
-	cp capstone/sysz_const.py $(OBJDIR)/pyx/sysz_const.pyx
-	cp capstone/x86.py $(OBJDIR)/pyx/x86.pyx
-	cp capstone/x86_const.py $(OBJDIR)/pyx/x86_const.pyx
-	cp capstone/xcore.py $(OBJDIR)/pyx/xcore.pyx
-	cp capstone/xcore_const.py $(OBJDIR)/pyx/xcore_const.pyx
-	cd $(OBJDIR) && python setup_cython.py build
+	mkdir -p $(PYX_BUILDDIR)/pyx
+	cp setup_cython.py $(PYX_BUILDDIR)
+	cp pyx/ccapstone* $(PYX_BUILDDIR)/pyx/
+	cp capstone/__init__.py $(PYX_BUILDDIR)/pyx/__init__.py
+	cp capstone/arm.py $(PYX_BUILDDIR)/pyx/arm.pyx
+	cp capstone/arm_const.py $(PYX_BUILDDIR)/pyx/arm_const.pyx
+	cp capstone/arm64.py $(PYX_BUILDDIR)/pyx/arm64.pyx
+	cp capstone/arm64_const.py $(PYX_BUILDDIR)/pyx/arm64_const.pyx
+	cp capstone/mips.py $(PYX_BUILDDIR)/pyx/mips.pyx
+	cp capstone/mips_const.py $(PYX_BUILDDIR)/pyx/mips_const.pyx
+	cp capstone/ppc.py $(PYX_BUILDDIR)/pyx/ppc.pyx
+	cp capstone/ppc_const.py $(PYX_BUILDDIR)/pyx/ppc_const.pyx
+	cp capstone/sparc.py $(PYX_BUILDDIR)/pyx/sparc.pyx
+	cp capstone/sparc_const.py $(PYX_BUILDDIR)/pyx/sparc_const.pyx
+	cp capstone/systemz.py $(PYX_BUILDDIR)/pyx/systemz.pyx
+	cp capstone/sysz_const.py $(PYX_BUILDDIR)/pyx/sysz_const.pyx
+	cp capstone/x86.py $(PYX_BUILDDIR)/pyx/x86.pyx
+	cp capstone/x86_const.py $(PYX_BUILDDIR)/pyx/x86_const.pyx
+	cp capstone/xcore.py $(PYX_BUILDDIR)/pyx/xcore.pyx
+	cp capstone/xcore_const.py $(PYX_BUILDDIR)/pyx/xcore_const.pyx
+	cd $(PYX_BUILDDIR) && python setup_cython.py build -b ./tmp install --home=$(PYX_BUILDDIR)
+	mv $(PYX_BUILDDIR)/build/lib/python/capstone/* capstone
+	cd $(PYX_BUILDDIR) && python setup_cython.py build -b ./tmp install
 
 # build & upload PyPi package with source code of the core
 sdist:
@@ -121,8 +89,8 @@
 	python3 setup.py sdist register upload
 
 clean:
-	rm -rf $(OBJDIR) src/ dist/ README
-	rm -f capstone/*.so
+	rm -rf $(PYX_BUILDDIR) build/ src/ dist/ *.egg-info README
+	rm -rf capstone/lib capstone/include
 	rm -rf prebuilt/win64/capstone.dll
 	rm -rf prebuilt/win32/capstone.dll
 
diff --git a/bindings/python/capstone/__init__.py b/bindings/python/capstone/__init__.py
index 62d57cd..6362659 100644
--- a/bindings/python/capstone/__init__.py
+++ b/bindings/python/capstone/__init__.py
@@ -233,66 +233,57 @@
 CS_OP    = {v:k for k,v in locals().items() if k.startswith('CS_OP_')}
 CS_OPT   = {v:k for k,v in locals().items() if k.startswith('CS_OPT_')}
 
-import ctypes, ctypes.util, sys
+import ctypes, ctypes.util
 from os.path import split, join, dirname
 import distutils.sysconfig
-
+import pkg_resources
 
 import inspect
 if not hasattr(sys.modules[__name__], '__file__'):
     __file__ = inspect.getfile(inspect.currentframe())
 
-_lib_path = split(__file__)[0]
-_all_libs = ['capstone.dll', 'libcapstone.so', 'libcapstone.dylib']
+if sys.platform == 'darwin':
+    _lib = "libcapstone.dylib"
+elif sys.platform in ('win32', 'cygwin'):
+    _lib = "capstone.dll"
+else:
+    _lib = "libcapstone.so"
+
+_all_libs = ['capstone.dll', 'libcapstone.so.3', 'libcapstone.so', 'libcapstone.dylib']
 _found = False
 
-for _lib in _all_libs:
+def _load_lib(path):
+    lib_file = join(path, _lib)
     try:
-        _lib_file = join(_lib_path, _lib)
-        # print "Trying to load:", _lib_file
-        _cs = ctypes.cdll.LoadLibrary(_lib_file)
-        _found = True
-        break
+        return ctypes.cdll.LoadLibrary(lib_file)
     except OSError:
-        pass
-if _found == False:
-    # try loading from default paths
-    for _lib in _all_libs:
-        try:
-            _cs = ctypes.cdll.LoadLibrary(_lib)
-            _found = True
-            break
-        except OSError:
-            pass
+        # if we're on linux, try again with .so.3 extension
+        if lib_file.endswith('.so'):
+            try:
+                return ctypes.cdll.LoadLibrary(lib_file)
+            except OSError:
+                return None
+        return None
 
-if _found == False:
-    # last try: loading from python lib directory
-    _lib_path = distutils.sysconfig.get_python_lib()
-    for _lib in _all_libs:
-        try:
-            _lib_file = join(_lib_path, 'capstone', _lib)
-            # print "Trying to load:", _lib_file
-            _cs = ctypes.cdll.LoadLibrary(_lib_file)
-            _found = True
-            break
-        except OSError:
-            pass
+_cs = None
 
-# Attempt Darwin specific load (10.11 specific),
-# since LD_LIBRARY_PATH is not guaranteed to exist
-if (_found == False) and (system() == 'Darwin'):
-    _lib_path = '/usr/local/lib/'
-    for _lib in _all_libs:
-        try:
-            _lib_file = join(_lib_path, _lib)
-            # print "Trying to load:", _lib_file
-            _cs = ctypes.cdll.LoadLibrary(_lib_file)
-            _found = True
-            break
-        except OSError:
-            pass
+# Loading attempts, in order
+# - pkg_resources can get us the path to the local libraries
+# - we can get the path to the local libraries by parsing our filename
+# - global load
+# - python's lib directory
+# - last-gasp attempt at some hardcoded paths on darwin and linux
 
-if _found == False:
+_path_list = [pkg_resources.resource_filename(__name__, 'lib'),
+              join(split(__file__)[0], 'lib'),
+              '',
+              distutils.sysconfig.get_python_lib(),
+              "/usr/local/lib/" if sys.platform == 'darwin' else '/usr/lib64']
+
+for _path in _path_list:
+    _cs = _load_lib(_path)
+    if _cs is not None: break
+else:
     raise ImportError("ERROR: fail to load the dynamic library.")
 
 
diff --git a/bindings/python/setup.py b/bindings/python/setup.py
index 9c1d422..9ab6c7b 100755
--- a/bindings/python/setup.py
+++ b/bindings/python/setup.py
@@ -1,51 +1,46 @@
 #!/usr/bin/env python
+
 import glob
 import os
 import shutil
 import stat
 import sys
+import platform
 
 from distutils import log
-from distutils import dir_util
-from distutils.command.build_clib import build_clib
-from setuptools.command.sdist import sdist
 from setuptools import setup
-from distutils.sysconfig import get_python_lib
-
-# prebuilt libraries for Windows - for sdist
-PATH_LIB64 = "prebuilt/win64/capstone.dll"
-PATH_LIB32 = "prebuilt/win32/capstone.dll"
-
-# package name can be 'capstone' or 'capstone-windows'
-PKG_NAME = 'capstone'
-if os.path.exists(PATH_LIB64) and os.path.exists(PATH_LIB32):
-    PKG_NAME = 'capstone-windows'
+from distutils.util import get_platform
+from distutils.command.build import build
+from distutils.command.sdist import sdist
+from setuptools.command.bdist_egg import bdist_egg
 
 SYSTEM = sys.platform
 VERSION = '4.0'
 
-# virtualenv breaks import, but get_python_lib() will work.
-SITE_PACKAGES = os.path.join(get_python_lib(), "capstone")
-if "--user" in sys.argv:
-    try:
-        from site import getusersitepackages
-        SITE_PACKAGES = os.path.join(getusersitepackages(), "capstone")
-    except ImportError:
-        pass
-
-# If building a wheel, the path listed in data_files is interpreted relative to
-# python's site-packages directory, even if it starts with a slash. So we need
-# to use only `/capstone` as path in this case.
-#
-# Note: using `capstone` does not work, since that for some reason is interpreted
-# relative to the the python installation prefix, not to the site-packages directory.
-if "bdist_wheel" in sys.argv:
-    SITE_PACKAGES = "/capstone"
-
-
 # adapted from commit e504b81 of Nguyen Tan Cong
 # Reference: https://docs.python.org/2/library/platform.html#cross-platform
-is_64bits = sys.maxsize > 2**32
+IS_64BITS = sys.maxsize > 2**32
+
+# are we building from the repository or from a source distribution?
+ROOT_DIR = os.path.dirname(os.path.realpath(__file__))
+LIBS_DIR = os.path.join(ROOT_DIR, 'capstone', 'lib')
+HEADERS_DIR = os.path.join(ROOT_DIR, 'capstone', 'include')
+SRC_DIR = os.path.join(ROOT_DIR, 'src')
+BUILD_DIR = SRC_DIR if os.path.exists(SRC_DIR) else os.path.join(ROOT_DIR, '../..')
+
+if SYSTEM == 'darwin':
+    LIBRARY_FILE = "libcapstone.dylib"
+    STATIC_LIBRARY_FILE = 'libcapstone.a'
+elif SYSTEM in ('win32', 'cygwin'):
+    LIBRARY_FILE = "capstone.dll"
+    STATIC_LIBRARY_FILE = None
+else:
+    LIBRARY_FILE = "libcapstone.so"
+    STATIC_LIBRARY_FILE = 'libcapstone.a'
+
+def clean_bins():
+    shutil.rmtree(LIBS_DIR, ignore_errors=True)
+    shutil.rmtree(HEADERS_DIR, ignore_errors=True)
 
 def copy_sources():
     """Copy the C sources into the source directory.
@@ -55,130 +50,128 @@
     src = []
 
     try:
-        dir_util.remove_tree("src/")
+        shutil.rmtree("src/")
     except (IOError, OSError):
         pass
 
-    dir_util.copy_tree("../../arch", "src/arch/")
-    dir_util.copy_tree("../../include", "src/include/")
-    if SYSTEM == "win32":
-        dir_util.copy_tree("../../msvc/headers", "src/msvc/headers")
+    shutil.copytree(os.path.join(BUILD_DIR, "arch"), os.path.join(SRC_DIR, "arch"))
+	shutil.copytree(os.path.join(BUILD_DIR, "include"), os.path.join(SRC_DIR, "include"))
 
-    src.extend(glob.glob("../../*.[ch]"))
-    src.extend(glob.glob("../../*.mk"))
+    src.extend(glob.glob(os.path.join(BUILD_DIR, "*.[ch]")))
+    src.extend(glob.glob(os.path.join(BUILD_DIR, "*.mk"))
 
-    src.extend(glob.glob("../../Makefile"))
-    src.extend(glob.glob("../../LICENSE*"))
-    src.extend(glob.glob("../../README"))
-    src.extend(glob.glob("../../*.TXT"))
-    src.extend(glob.glob("../../RELEASE_NOTES"))
-    src.extend(glob.glob("../../make.sh"))
-    src.extend(glob.glob("../../CMakeLists.txt"))
+    src.extend(glob.glob(os.path.join(BUILD_DIR, "Makefile"))
+    src.extend(glob.glob(os.path.join(BUILD_DIR, "LICENSE*"))
+    src.extend(glob.glob(os.path.join(BUILD_DIR, "README"))
+    src.extend(glob.glob(os.path.join(BUILD_DIR, "*.TXT"))
+    src.extend(glob.glob(os.path.join(BUILD_DIR, "RELEASE_NOTES"))
+    src.extend(glob.glob(os.path.join(BUILD_DIR, "make.sh"))
+    src.extend(glob.glob(os.path.join(BUILD_DIR, "CMakeLists.txt"))
 
     for filename in src:
-        outpath = os.path.join("./src/", os.path.basename(filename))
+        outpath = os.path.join(SRC_DIR, os.path.basename(filename))
         log.info("%s -> %s" % (filename, outpath))
         shutil.copy(filename, outpath)
 
+def build_libraries():
+    """
+    Prepare the capstone directory for a binary distribution or installation.
+    Builds shared libraries and copies header files.
+
+    Will use a src/ dir if one exists in the current directory, otherwise assumes it's in the repo
+    """
+    cwd = os.getcwd()
+    clean_bins()
+    os.mkdir(HEADERS_DIR)
+    os.mkdir(LIBS_DIR)
+
+    # copy public headers
+    shutil.copytree(os.path.join(BUILD_DIR, 'include'), os.path.join(HEADERS_DIR, 'capstone'))
+
+    os.chdir(BUILD_DIR)
+
+    # platform description refers at https://docs.python.org/2/library/sys.html#sys.platform
+    if SYSTEM == "win32":
+        # Windows build: this process requires few things:
+        #    - CMake + MSVC installed
+        #    - Run this command in an environment setup for MSVC
+        if not os.path.exists("build"): os.mkdir("build")
+        os.chdir("build")
+        # Do not build tests & static library
+        os.system('cmake -DCMAKE_BUILD_TYPE=RELEASE -DCAPSTONE_BUILD_TESTS=0 -DCAPSTONE_BUILD_STATIC=0 -G "NMake Makefiles" ..')
+        os.system("nmake")
+    elif SYSTEM == "cygwin":
+        os.chmod("make.sh", stat.S_IREAD|stat.S_IEXEC)
+        if is_64bits:
+            os.system("CAPSTONE_BUILD_CORE_ONLY=yes ./make.sh cygwin-mingw64")
+        else:
+            os.system("CAPSTONE_BUILD_CORE_ONLY=yes ./make.sh cygwin-mingw32")
+
+        so = "capstone.dll"
+    else:   # Unix
+        os.system("CAPSTONE_BUILD_CORE_ONLY=yes ./make.sh")
+
+    shutil.copy(LIBRARY_FILE, LIBS_DIR)
+    if STATIC_LIBRARY_FILE: shutil.copy(STATIC_LIBRARY_FILE, LIBS_DIR)
+    os.chdir(cwd)
+
 
 class custom_sdist(sdist):
-    """Reshuffle files for distribution."""
-
     def run(self):
-        for filename in (glob.glob("capstone/*.dll")
-                         + glob.glob("capstone/*.so")
-                         + glob.glob("capstone/*.dylib")):
-            try:
-                os.unlink(filename)
-            except Exception:
-                pass
-
-        # if prebuilt libraries are existent, then do not copy source
-        if os.path.exists(PATH_LIB64) and os.path.exists(PATH_LIB32):
-            return sdist.run(self)
+        clean_bins()
         copy_sources()
         return sdist.run(self)
 
 
-class custom_build_clib(build_clib):
-    """Customized build_clib command."""
-
+class custom_build(build):
     def run(self):
-        log.info('running custom_build_clib')
-        build_clib.run(self)
+        log.info('Building C extensions')
+        build_libraries()
+        return build.run(self)
 
-    def finalize_options(self):
-        # We want build-clib to default to build-lib as defined by the "build"
-        # command.  This is so the compiled library will be put in the right
-        # place along side the python code.
-        self.set_undefined_options('build',
-                                   ('build_lib', 'build_clib'),
-                                   ('build_temp', 'build_temp'),
-                                   ('compiler', 'compiler'),
-                                   ('debug', 'debug'),
-                                   ('force', 'force'))
 
-        build_clib.finalize_options(self)
-
-    def build_libraries(self, libraries):
-        if SYSTEM in ("win32", "cygwin"):
-            # if Windows prebuilt library is available, then include it
-            if is_64bits and os.path.exists(PATH_LIB64):
-                shutil.copy(PATH_LIB64, "capstone")
-                return
-            elif os.path.exists(PATH_LIB32):
-                shutil.copy(PATH_LIB32, "capstone")
-                return
-
-        # build library from source if src/ is existent
-        if not os.path.exists('src'):
-            return
-
-        for (lib_name, build_info) in libraries:
-            log.info("building '%s' library", lib_name)
-
-            os.chdir("src")
-
-            # platform description refers at https://docs.python.org/2/library/sys.html#sys.platform
-            if SYSTEM == "win32":
-                # Windows build: this process requires few things:
-                #    - CMake + MSVC installed
-                #    - Run this command in an environment setup for MSVC
-                os.mkdir("build")
-                os.chdir("build")
-                # Do not build tests & static library
-                os.system('cmake -DCMAKE_BUILD_TYPE=RELEASE -DCAPSTONE_BUILD_TESTS=0 -DCAPSTONE_BUILD_STATIC=0 -G "NMake Makefiles" ..')
-                os.system("nmake")
-                os.chdir("..")
-                so = "src/build/capstone.dll"
-            elif SYSTEM == "cygwin":
-                os.chmod("make.sh", stat.S_IREAD|stat.S_IEXEC)
-                if is_64bits:
-                    os.system("CAPSTONE_BUILD_CORE_ONLY=yes ./make.sh cygwin-mingw64")
-                else:
-                    os.system("CAPSTONE_BUILD_CORE_ONLY=yes ./make.sh cygwin-mingw32")
-
-                so = "src/capstone.dll"
-            else:   # Unix
-                os.chmod("make.sh", stat.S_IREAD|stat.S_IEXEC)
-                os.system("CAPSTONE_BUILD_CORE_ONLY=yes ./make.sh")
-                if SYSTEM == "darwin":
-                    so = "src/libcapstone.dylib"
-                else:   # Non-OSX
-                    so = "src/libcapstone.so"
-
-            os.chdir("..")
-            shutil.copy(so, "capstone")
-
+class custom_bdist_egg(bdist_egg):
+    def run(self):
+        self.run_command('build')
+        return bdist_egg.run(self)
 
 def dummy_src():
     return []
 
+cmdclass = {}
+cmdclass['build'] = custom_build
+cmdclass['sdist'] = custom_sdist
+cmdclass['bdist_egg'] = custom_bdist_egg
+
+try:
+    from setuptools.command.develop import develop
+    class custom_develop(develop):
+        def run(self):
+            log.info("Building C extensions")
+            build_libraries()
+            return develop.run(self)
+
+    cmdclass['develop'] = custom_develop
+except ImportError:
+    print "Proper 'develop' support unavailable."
+
+if 'bdist_wheel' in sys.argv and '--plat-name' not in sys.argv:
+    sys.argv.append('--plat-name')
+    name = get_platform()
+    if 'linux' in name:
+        # linux_* platform tags are disallowed because the python ecosystem is fubar
+        # linux builds should be built in the centos 5 vm for maximum compatibility
+        # see https://github.com/pypa/manylinux
+        # see also https://github.com/angr/angr-dev/blob/master/bdist.sh
+        sys.argv.append('manylinux1_' + platform.machine())
+    else:
+        # https://www.python.org/dev/peps/pep-0425/
+        sys.argv.append(name.replace('.', '_').replace('-', '_'))
 
 setup(
     provides=['capstone'],
     packages=['capstone'],
-    name=PKG_NAME,
+    name='capstone',
     version=VERSION,
     author='Nguyen Anh Quynh',
     author_email='aquynh@gmail.com',
@@ -190,20 +183,10 @@
         'Programming Language :: Python :: 3',
     ],
     requires=['ctypes'],
-    cmdclass=dict(
-        build_clib=custom_build_clib,
-        sdist=custom_sdist,
-    ),
-
-    libraries=[(
-        'capstone', dict(
-            package='capstone',
-            sources=dummy_src()
-        ),
-    )],
-    zip_safe=False,
+    cmdclass=cmdclass,
+    zip_safe=True,
     include_package_data=True,
     package_data={
-        "capstone": ["*.so", "*.dll", "*.dylib"],
+        "capstone": ["lib/*", "include/capstone/*"],
     }
 )