Contributes to ticket 795. Mostly a rewrite of the changes committed in r7450. Contains an extra mass balance fix compared to r7450