Cleaned up a lot and added some comments.