lots more refactoring and cleanup