Quite often are nested if-loops a nightmare from a performance and developing/maintaining point of view and shouldn't be used so heavily like in your example. I think you will need to change these expression at least by replacing the if-loop with something like this:
Thanks for your inputs. Your suggestions has significantly simplified the script and I'm happy about it. However, the expression doesn't accept the Average function. I tested it in a textbox which give me this message "Error is expression: Nested aggregation not allowed". Any idea?!