rewrote phi optimization with loads of debug output