Bugfixes and small refactorings...
Tests for sapi.