giant ugly optimize function