cleaned up some code and added a few comments. I also changed the logic to be closer to what we want.