significant code cleanup and refactoring