Cleaned up code and added some comments