Move some code around; cleanup a bit.