refactored to use less if statements and avoid duplication of code