Re-factored and optimized