Replace the C extension with a much better implementation

Special thanks to @nobu! I spent many hours on writing the extension and
ended up having +10000 lines of code, but he did it in 10mins with just
about 20 lines of code!