Further refactoring and cleanup