Cleaned up the code, simplified a few functions, added some comments.