Extracted all the calculation code.

It's now in a library file that still needs to be checked in.