Added more documentation, and separated the code out so it's cleaner/easier to understand.