Refactored and optimized a bit