Some refactoring for reducing code duplication and making functions smaller.