Cleaned up code in places and added comments.