Version 2, optimized, refactored