Finished and optimized version