More testing, some bugfixes. Close to working correctly in most cases,
not yet sure what the problem is though. #165