Big refactoring and cleanup
further refinements