Some refactoring. And a bug fix.