Major refactoring. Minor cleanup may be necessary (names etc.)