Updated to improve efficiency and remove errors