Moving some of @jisaacson's code in (with edits)