huge refactoring and cleanup