Factored out some code, fixed comments.