This function, `compute_output`, has more than 400 lines (!).  It is very hard to follow what it's doing, let alone whether it's doing it right :) At least for me.  Could we split it in half a dozen smaller functions?