Refactored and optimized magic