refactored optimization logic to more closely resemble opt