Improved code to make more efficient