Cleaned up some code to make it simpler to split into multiple modules.