Added more comments explaining the code.
Moved most of the actual work into functions.