Added most of the opt code