Minor code cleanup.
Split the code into multiple function for the sake of clarity.