Move some loops up to be faster.
Revert "Move some loops up to be faster."

This reverts commit eda00caddc058c47de9df8382532c00065f80546.
Some mods
upstream