Refactored the code slightly so that pieces are more logically defined.