heavy refactoring and cleanup