Bug fixes and tests