Lots of fixes, added tests