Various bug fixes and improved tests