Major refactoring using helper functions