Some code refactoring and bugfixes.