Code from Dan Hodges and Andrew Borgmann's work.