Many bugfixes. Improved testing coverage.