Factored out some redundant code. Added a few comments.