Fixed a number of things and optimized the abstraction. Works, but still too slow for some test cases.
#1: improved performance quite a bit
#2: added some more test cases