Fixed ternary conditions and refactored duplicate code