Extracted some code into separate functions from main().