code cleanup and comments

added comments and factored things out into more functions