Added some comments cleaned up the logic a bit.