cleaned things up a little (no, I didn't get rid of some of the repeated functions) and added plenty of comments