Some minor refactoring and bug fixing.