Moved a whack of code around into module form.