Code from old simulations, imported here to clean up and refine