Working code that's optimized