Added a few comments and shuffled the code around for readability.