cleaned up code and added some comments