More bits borrowed nearly verbatim from @jyasskin's work.