Major refactoring to remove duplicate code