Further refactoring to make the script more usable as a library.