Changed many loops to iterators, improved commenting, caught a couple of bugs