More cleaning up; factor out optimizer to new file. Some weird problems still.