major refactoring and code cleanup