Fix many bugs and revamp the test suite. Not complete yet.