Credit to Tim Rodenbröker for many of the ideas here.