Cleaned up code a little and added some comments