Move some chunks of code around and rename a couple of functions in order to be closer to bug 21446.