Cleanup, refactoring and bugfix.