added comments, reorganized code