added comments and reorganized code