Refactoring for clarity plus some minor bug fixes.