Some slight refactoring to use lambdas and a few minor sanity checks