Some more refactoring and tweaks to clean up the code a bit.