cleaned up the code a bit and added some comments