Factored out some code, added a couple methods and some notes (entered as comments).