Updated code to make it more efficient and accurate