Made it more logical and added comments.