Big refactoring and small bug fixes.