Refactoring and tests for the api interface.
Some other minor tweaks.