Clean up of main function by replacing code snippets with external functions.