made code simpler and added comments explaining what is happening