fix another sanity error, and refactor/tidy up