Have you tried creating flags in the script?
When you run script it should create 0/1 flags for each condition applyable to each term in your calculation.
Then the calculations inside the charts became as easy as
"sum(Term1 * flagTotal) + sum(Term2 * flagTotal)"
"sum(Term1 * flagOverall) + sum(Term2 * flagOverall)"
In other words, when you are reading the table with the values you can analyze, line by line, if it should be part of an expressions calculation. The flag in this case should be 1. And you may create one ore more flags for each expression.
It´s a little confusing, but the important is to get the idea.