This is an extremely expensive loop - would be better to rewrite it.