Removing code duplication, and logic errors