Significant refactoring and code cleanup