This is copied from optimize.py right? Better to factor that out into a common file, rather then duplicate.