Refactor for most of the functions.

Split them into smaller functions..