implement calculation of balance functions

Can you tell me whether this looks good? (The code compiles, it is untested however.)