added comments, moved some code around