Cleaned up code and added a few more comments for clarity.