Major code overhaul. Tests pass.