Thanks Oskars, the change you suggested solved my problem. But as you mentioned it becomes slow and most of the times gives me out of time error.
There is another thread already opened for the optimization of this measure. Please do have a look and let me know if you have any further suggestions.