Cleaned up code and added a lot of comments.