Rearranged code for easier unit testing.