added some commentary and moved the helper functions to the bottom of the file