clean up algorithm and remove operand order assumptions