Revised code to make it more efficient