I've commented the utility functions as best I can.