PROG: finished inner optimization code. IT IS UNTESTED