Major code refactoring