Big refactor to make code more modular, in preparation for introducing the JIT-compiled HMC kernel.