added comments, removed repeated code