final code tested and optimized