Confirmed code functionality, edited for readability