Yes, I see it has to be sample by sample, but the code can be rewritten to avoid those SLOW function calls from within the inner loop.

-ml