Numerous fixes and tests