Refactoring.

Merged some functionality into functions for better reuse of code.