Refactoring. Plus some fixes.