finished optimized version