Major code refactoring and cleanup