# Fix for bus error issues when compiling cpython extensions in pyrp3 v1.2.0+
# Patch sourced from: https://github.com/linien-org/pyrp3/tree/e6688acf8bd79d2dbe1d192d09c1a1baf1f6c67b (setup.py & monitor/Makefile)
# Reference: https://github.com/elhep/Fast-Servo-Firmware/blob/master/OS/scripts/linien_install_requirements.sh#L28

diff --git a/monitor/Makefile b/monitor/Makefile
new file mode 100644
index 0000000..0c9bb53
--- /dev/null
+++ b/monitor/Makefile
@@ -0,0 +1,31 @@
+# Makefile for libmonitor
+
+OBJS = monitor.o
+SRCS = $(subst .o,.c, $(OBJS)))
+OSOBJS = monitor.os
+TARGETLIB=libmonitor.so
+CFLAGS=-g -std=gnu99 -Wall -Werror
+LIBS=-lm -lpthread
+
+# Use CROSS_COMPILE=arm-linux-gnueabi-
+CC=$(CROSS_COMPILE)gcc
+INSTALL_DIR ?= .
+
+
+all: $(TARGETLIB)
+lib: $(TARGETLIB)
+
+%.os: %.c
+	$(CC) -c -fPIC $(CFLAGS) $< -o $@
+
+$(TARGETLIB): $(OSOBJS)
+	$(CC) -o $@ -shared $^ $(CFLAGS) $(LIBS)
+
+clean:
+	rm -f $(TARGETLIB) *.o *.os
+
+# Install target - creates 'lib/' sub-directory in $(INSTALL_DIR) and copies all
+# executables to that location.
+install:
+	mkdir -p $(INSTALL_DIR)/lib
+	cp $(TARGETLIB) $(INSTALL_DIR)/lib
\ No newline at end of file
diff --git a/pyrp3/raw_memory.py b/pyrp3/raw_memory.py
index ce1b28e..233b82a 100644
--- a/pyrp3/raw_memory.py
+++ b/pyrp3/raw_memory.py
@@ -1,12 +1,9 @@
 from ctypes import POINTER, c_uint32, cast, cdll, create_string_buffer, sizeof
-from importlib.machinery import EXTENSION_SUFFIXES
 from pathlib import Path
 
 import numpy as np
 
-libmonitor_file = str(
-    Path(__file__).parent / ".." / "monitor{}".format(EXTENSION_SUFFIXES[0])
-)
+libmonitor_file = 'libmonitor.so'
 
 libmonitor = cdll.LoadLibrary(libmonitor_file)
 libmonitor.read_value.restype = c_uint32
diff --git a/setup.py b/setup.py
index 9302177..2258ddc 100644
--- a/setup.py
+++ b/setup.py
@@ -1,4 +1,28 @@
-from distutils.core import Extension, setup
+import os
+from distutils.core import setup
+from distutils.command.build import build
+
+
+build_dir = "monitor/"
+
+def compile_libmonitor():
+    cwd = os.getcwd()  # get current directory
+    try:
+        os.chdir(build_dir)
+        os.system("make clean")
+        os.system("make all")
+    finally:
+        os.chdir(cwd)
+
+class lib_build(build):
+    def run(self):
+        compile_libmonitor()
+        build.run(self)
+
+setup_args = dict(
+    cmdclass={
+        "build": lib_build
+    }
+)
 
-setup_args = dict(ext_modules=[Extension("monitor", ["monitor/monitor.c"])])
 setup(**setup_args)