finished and optimized code