Copied in some math that I haven't tested yet.