Major refactoring.  Put boilerplate code into utility functions