Add documentation. Pull out some functions and constants.