Many bug fixes and extension of tests