Tidy up a bit.
Pull out some functions to a separate module.