Most of the code in this file should be moved into separate functions.